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"
272ec34544SRui Ueyama #include "llvm/ADT/StringSwitch.h"
28*264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
292ec34544SRui Ueyama #include "llvm/Support/Casting.h"
302ec34544SRui Ueyama #include "llvm/Support/ErrorHandling.h"
312ec34544SRui Ueyama #include "llvm/Support/FileSystem.h"
322ec34544SRui Ueyama #include "llvm/Support/Path.h"
332ec34544SRui Ueyama #include <cassert>
342ec34544SRui Ueyama #include <limits>
352ec34544SRui Ueyama #include <vector>
362ec34544SRui Ueyama 
372ec34544SRui Ueyama using namespace llvm;
382ec34544SRui Ueyama using namespace llvm::ELF;
39b58079d4SRui Ueyama using namespace llvm::support::endian;
402ec34544SRui Ueyama using namespace lld;
412ec34544SRui Ueyama using namespace lld::elf;
422ec34544SRui Ueyama 
432ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path);
442ec34544SRui Ueyama 
4596b3fe02SRui Ueyama namespace {
4696b3fe02SRui Ueyama class ScriptParser final : ScriptLexer {
472ec34544SRui Ueyama public:
482ec34544SRui Ueyama   ScriptParser(MemoryBufferRef MB)
492ec34544SRui Ueyama       : ScriptLexer(MB),
502ec34544SRui Ueyama         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
512ec34544SRui Ueyama 
522ec34544SRui Ueyama   void readLinkerScript();
532ec34544SRui Ueyama   void readVersionScript();
542ec34544SRui Ueyama   void readDynamicList();
552ec34544SRui Ueyama 
562ec34544SRui Ueyama private:
572ec34544SRui Ueyama   void addFile(StringRef Path);
5805c4f67cSRafael Espindola   OutputSection *checkSection(OutputSectionCommand *Cmd, StringRef Loccation);
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();
702ec34544SRui Ueyama   void readSearchDir();
712ec34544SRui Ueyama   void readSections();
722ec34544SRui Ueyama   void readVersion();
732ec34544SRui Ueyama   void readVersionScriptCommand();
742ec34544SRui Ueyama 
752ec34544SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
762ec34544SRui Ueyama   BytesDataCommand *readBytesDataCommand(StringRef Tok);
772ec34544SRui Ueyama   uint32_t readFill();
788acbf1ccSRui Ueyama   uint32_t parseFill(StringRef Tok);
792ec34544SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
802ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
812ec34544SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef Tok);
822ec34544SRui Ueyama   StringMatcher readFilePatterns();
832ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
842ec34544SRui Ueyama   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
852ec34544SRui Ueyama   unsigned readPhdrType();
862ec34544SRui Ueyama   SortSectionPolicy readSortKind();
872ec34544SRui Ueyama   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
882ec34544SRui Ueyama   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
892ec34544SRui Ueyama   void readSort();
9023af89ccSRui Ueyama   AssertCommand *readAssert();
9123af89ccSRui Ueyama   Expr readAssertExpr();
922ec34544SRui Ueyama 
932ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
942ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
952ec34544SRui Ueyama 
962ec34544SRui Ueyama   Expr readExpr();
972ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
982ec34544SRui Ueyama   StringRef readParenLiteral();
992ec34544SRui Ueyama   Expr readPrimary();
1002ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1012ec34544SRui Ueyama   Expr readParenExpr();
1022ec34544SRui Ueyama 
1032ec34544SRui Ueyama   // For parsing version script.
1042ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1052ec34544SRui Ueyama   void readAnonymousDeclaration();
1062ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1072ec34544SRui Ueyama 
1082ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1092ec34544SRui Ueyama   readSymbols();
1102ec34544SRui Ueyama 
1112ec34544SRui Ueyama   bool IsUnderSysroot;
1122ec34544SRui Ueyama };
11396b3fe02SRui Ueyama } // namespace
1142ec34544SRui Ueyama 
1152ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1162ec34544SRui Ueyama   if (Config->Sysroot == "")
1172ec34544SRui Ueyama     return false;
1182ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1192ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1202ec34544SRui Ueyama       return true;
1212ec34544SRui Ueyama   return false;
1222ec34544SRui Ueyama }
1232ec34544SRui Ueyama 
1242ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1252ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1262ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
1272ec34544SRui Ueyama   if (A.isAbsolute())
1282ec34544SRui Ueyama     std::swap(A, B);
1292ec34544SRui Ueyama   if (!B.isAbsolute())
1302ec34544SRui Ueyama     error("At least one side of the expression must be absolute");
1312ec34544SRui Ueyama }
1322ec34544SRui Ueyama 
1332ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1342ec34544SRui Ueyama   moveAbsRight(A, B);
1352ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute, A.Val + B.getValue()};
1362ec34544SRui Ueyama }
1372ec34544SRui Ueyama 
1382ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
1392ec34544SRui Ueyama   return {A.Sec, A.Val - B.getValue()};
1402ec34544SRui Ueyama }
1412ec34544SRui Ueyama 
1422ec34544SRui Ueyama static ExprValue mul(ExprValue A, ExprValue B) {
1432ec34544SRui Ueyama   return A.getValue() * B.getValue();
1442ec34544SRui Ueyama }
1452ec34544SRui Ueyama 
1462ec34544SRui Ueyama static ExprValue div(ExprValue A, ExprValue B) {
1472ec34544SRui Ueyama   if (uint64_t BV = B.getValue())
1482ec34544SRui Ueyama     return A.getValue() / BV;
1492ec34544SRui Ueyama   error("division by zero");
1502ec34544SRui Ueyama   return 0;
1512ec34544SRui Ueyama }
1522ec34544SRui Ueyama 
1532ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1542ec34544SRui Ueyama   moveAbsRight(A, B);
1552ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
1562ec34544SRui Ueyama           (A.getValue() & B.getValue()) - A.getSecAddr()};
1572ec34544SRui Ueyama }
1582ec34544SRui Ueyama 
1592ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1602ec34544SRui Ueyama   moveAbsRight(A, B);
1612ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
1622ec34544SRui Ueyama           (A.getValue() | B.getValue()) - A.getSecAddr()};
1632ec34544SRui Ueyama }
1642ec34544SRui Ueyama 
1652ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1662ec34544SRui Ueyama   expect("{");
1672ec34544SRui Ueyama   readAnonymousDeclaration();
1682ec34544SRui Ueyama   if (!atEOF())
1692ec34544SRui Ueyama     setError("EOF expected, but got " + next());
1702ec34544SRui Ueyama }
1712ec34544SRui Ueyama 
1722ec34544SRui Ueyama void ScriptParser::readVersionScript() {
1732ec34544SRui Ueyama   readVersionScriptCommand();
1742ec34544SRui Ueyama   if (!atEOF())
1752ec34544SRui Ueyama     setError("EOF expected, but got " + next());
1762ec34544SRui Ueyama }
1772ec34544SRui Ueyama 
1782ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
1792ec34544SRui Ueyama   if (consume("{")) {
1802ec34544SRui Ueyama     readAnonymousDeclaration();
1812ec34544SRui Ueyama     return;
1822ec34544SRui Ueyama   }
1832ec34544SRui Ueyama 
1842ec34544SRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
1852ec34544SRui Ueyama     StringRef VerStr = next();
1862ec34544SRui Ueyama     if (VerStr == "{") {
1872ec34544SRui Ueyama       setError("anonymous version definition is used in "
1882ec34544SRui Ueyama                "combination with other version definitions");
1892ec34544SRui Ueyama       return;
1902ec34544SRui Ueyama     }
1912ec34544SRui Ueyama     expect("{");
1922ec34544SRui Ueyama     readVersionDeclaration(VerStr);
1932ec34544SRui Ueyama   }
1942ec34544SRui Ueyama }
1952ec34544SRui Ueyama 
1962ec34544SRui Ueyama void ScriptParser::readVersion() {
1972ec34544SRui Ueyama   expect("{");
1982ec34544SRui Ueyama   readVersionScriptCommand();
1992ec34544SRui Ueyama   expect("}");
2002ec34544SRui Ueyama }
2012ec34544SRui Ueyama 
2022ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2032ec34544SRui Ueyama   while (!atEOF()) {
2042ec34544SRui Ueyama     StringRef Tok = next();
2052ec34544SRui Ueyama     if (Tok == ";")
2062ec34544SRui Ueyama       continue;
2072ec34544SRui Ueyama 
2082ec34544SRui Ueyama     if (Tok == "ASSERT") {
20923af89ccSRui Ueyama       Script->Opt.Commands.push_back(readAssert());
2102ec34544SRui Ueyama     } else if (Tok == "ENTRY") {
2112ec34544SRui Ueyama       readEntry();
2122ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2132ec34544SRui Ueyama       readExtern();
2142ec34544SRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
2152ec34544SRui Ueyama       readGroup();
2162ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2172ec34544SRui Ueyama       readInclude();
2182ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2192ec34544SRui Ueyama       readMemory();
2202ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2212ec34544SRui Ueyama       readOutput();
2222ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2232ec34544SRui Ueyama       readOutputArch();
2242ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2252ec34544SRui Ueyama       readOutputFormat();
2262ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2272ec34544SRui Ueyama       readPhdrs();
2282ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2292ec34544SRui Ueyama       readSearchDir();
2302ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2312ec34544SRui Ueyama       readSections();
2322ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2332ec34544SRui Ueyama       readVersion();
2342ec34544SRui Ueyama     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
2352ec34544SRui Ueyama       Script->Opt.Commands.push_back(Cmd);
2362ec34544SRui Ueyama     } else {
2372ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2382ec34544SRui Ueyama     }
2392ec34544SRui Ueyama   }
2402ec34544SRui Ueyama }
2412ec34544SRui Ueyama 
2422ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2432ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2442ec34544SRui Ueyama     SmallString<128> PathData;
2452ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2462ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
247a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2482ec34544SRui Ueyama       return;
2492ec34544SRui Ueyama     }
2502ec34544SRui Ueyama   }
2512ec34544SRui Ueyama 
2522ec34544SRui Ueyama   if (sys::path::is_absolute(S)) {
253a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2542ec34544SRui Ueyama   } else if (S.startswith("=")) {
2552ec34544SRui Ueyama     if (Config->Sysroot.empty())
256a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
2572ec34544SRui Ueyama     else
258a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
259a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
2602ec34544SRui Ueyama   } else if (S.startswith("-l")) {
2612ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
2622ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
263a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2642ec34544SRui Ueyama   } else {
2652ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
266a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
2672ec34544SRui Ueyama     else
2682ec34544SRui Ueyama       setError("unable to find " + S);
2692ec34544SRui Ueyama   }
2702ec34544SRui Ueyama }
2712ec34544SRui Ueyama 
2722ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
2732ec34544SRui Ueyama   expect("(");
2742ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
2752ec34544SRui Ueyama   Config->AsNeeded = true;
2762ec34544SRui Ueyama   while (!Error && !consume(")"))
2772ec34544SRui Ueyama     addFile(unquote(next()));
2782ec34544SRui Ueyama   Config->AsNeeded = Orig;
2792ec34544SRui Ueyama }
2802ec34544SRui Ueyama 
2812ec34544SRui Ueyama void ScriptParser::readEntry() {
2822ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
2832ec34544SRui Ueyama   expect("(");
2842ec34544SRui Ueyama   StringRef Tok = next();
2852ec34544SRui Ueyama   if (Config->Entry.empty())
2862ec34544SRui Ueyama     Config->Entry = Tok;
2872ec34544SRui Ueyama   expect(")");
2882ec34544SRui Ueyama }
2892ec34544SRui Ueyama 
2902ec34544SRui Ueyama void ScriptParser::readExtern() {
2912ec34544SRui Ueyama   expect("(");
2922ec34544SRui Ueyama   while (!Error && !consume(")"))
2932ec34544SRui Ueyama     Config->Undefined.push_back(next());
2942ec34544SRui Ueyama }
2952ec34544SRui Ueyama 
2962ec34544SRui Ueyama void ScriptParser::readGroup() {
2972ec34544SRui Ueyama   expect("(");
2982ec34544SRui Ueyama   while (!Error && !consume(")")) {
299b579c439SRui Ueyama     if (consume("AS_NEEDED"))
3002ec34544SRui Ueyama       readAsNeeded();
3012ec34544SRui Ueyama     else
302b579c439SRui Ueyama       addFile(unquote(next()));
3032ec34544SRui Ueyama   }
3042ec34544SRui Ueyama }
3052ec34544SRui Ueyama 
3062ec34544SRui Ueyama void ScriptParser::readInclude() {
3072ec34544SRui Ueyama   StringRef Tok = unquote(next());
3082ec34544SRui Ueyama 
3092ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/File-Commands.html:
3102ec34544SRui Ueyama   // The file will be searched for in the current directory, and in any
3112ec34544SRui Ueyama   // directory specified with the -L option.
3122ec34544SRui Ueyama   if (sys::fs::exists(Tok)) {
3132ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(Tok))
3142ec34544SRui Ueyama       tokenize(*MB);
3152ec34544SRui Ueyama     return;
3162ec34544SRui Ueyama   }
3172ec34544SRui Ueyama   if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
3182ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3192ec34544SRui Ueyama       tokenize(*MB);
3202ec34544SRui Ueyama     return;
3212ec34544SRui Ueyama   }
3222ec34544SRui Ueyama   setError("cannot open " + Tok);
3232ec34544SRui Ueyama }
3242ec34544SRui Ueyama 
3252ec34544SRui Ueyama void ScriptParser::readOutput() {
3262ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3272ec34544SRui Ueyama   expect("(");
3282ec34544SRui Ueyama   StringRef Tok = next();
3292ec34544SRui Ueyama   if (Config->OutputFile.empty())
3302ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3312ec34544SRui Ueyama   expect(")");
3322ec34544SRui Ueyama }
3332ec34544SRui Ueyama 
3342ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3352ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3362ec34544SRui Ueyama   expect("(");
3372ec34544SRui Ueyama   while (!Error && !consume(")"))
3382ec34544SRui Ueyama     skip();
3392ec34544SRui Ueyama }
3402ec34544SRui Ueyama 
3412ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3422ec34544SRui Ueyama   // Error checking only for now.
3432ec34544SRui Ueyama   expect("(");
3442ec34544SRui Ueyama   skip();
345b579c439SRui Ueyama   if (consume(")"))
3462ec34544SRui Ueyama     return;
347b579c439SRui Ueyama   expect(",");
3482ec34544SRui Ueyama   skip();
3492ec34544SRui Ueyama   expect(",");
3502ec34544SRui Ueyama   skip();
3512ec34544SRui Ueyama   expect(")");
3522ec34544SRui Ueyama }
3532ec34544SRui Ueyama 
3542ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3552ec34544SRui Ueyama   expect("{");
3562ec34544SRui Ueyama   while (!Error && !consume("}")) {
3572ec34544SRui Ueyama     Script->Opt.PhdrsCommands.push_back(
358b579c439SRui Ueyama         {next(), PT_NULL, false, false, UINT_MAX, nullptr});
3592ec34544SRui Ueyama 
360b579c439SRui Ueyama     PhdrsCommand &PhdrCmd = Script->Opt.PhdrsCommands.back();
3612ec34544SRui Ueyama     PhdrCmd.Type = readPhdrType();
362b579c439SRui Ueyama 
363b579c439SRui Ueyama     while (!Error && !consume(";")) {
364b579c439SRui Ueyama       if (consume("FILEHDR"))
3652ec34544SRui Ueyama         PhdrCmd.HasFilehdr = true;
366b579c439SRui Ueyama       else if (consume("PHDRS"))
3672ec34544SRui Ueyama         PhdrCmd.HasPhdrs = true;
368b579c439SRui Ueyama       else if (consume("AT"))
3692ec34544SRui Ueyama         PhdrCmd.LMAExpr = readParenExpr();
370b579c439SRui Ueyama       else if (consume("FLAGS"))
371b579c439SRui Ueyama         PhdrCmd.Flags = readParenExpr()().getValue();
372b579c439SRui Ueyama       else
373b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
374b579c439SRui Ueyama     }
3752ec34544SRui Ueyama   }
3762ec34544SRui Ueyama }
3772ec34544SRui Ueyama 
3782ec34544SRui Ueyama void ScriptParser::readSearchDir() {
3792ec34544SRui Ueyama   expect("(");
3802ec34544SRui Ueyama   StringRef Tok = next();
3812ec34544SRui Ueyama   if (!Config->Nostdlib)
3822ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
3832ec34544SRui Ueyama   expect(")");
3842ec34544SRui Ueyama }
3852ec34544SRui Ueyama 
3862ec34544SRui Ueyama void ScriptParser::readSections() {
3872ec34544SRui Ueyama   Script->Opt.HasSections = true;
388b579c439SRui Ueyama 
3892ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
3902ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
3912ec34544SRui Ueyama   // script. See comment for computeFlags().
3922ec34544SRui Ueyama   Config->SingleRoRx = true;
3932ec34544SRui Ueyama 
3942ec34544SRui Ueyama   expect("{");
3952ec34544SRui Ueyama   while (!Error && !consume("}")) {
3962ec34544SRui Ueyama     StringRef Tok = next();
3972ec34544SRui Ueyama     BaseCommand *Cmd = readProvideOrAssignment(Tok);
3982ec34544SRui Ueyama     if (!Cmd) {
3992ec34544SRui Ueyama       if (Tok == "ASSERT")
40023af89ccSRui Ueyama         Cmd = readAssert();
4012ec34544SRui Ueyama       else
4022ec34544SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
4032ec34544SRui Ueyama     }
4042ec34544SRui Ueyama     Script->Opt.Commands.push_back(Cmd);
4052ec34544SRui Ueyama   }
4062ec34544SRui Ueyama }
4072ec34544SRui Ueyama 
4082ec34544SRui Ueyama static int precedence(StringRef Op) {
4092ec34544SRui Ueyama   return StringSwitch<int>(Op)
4102ec34544SRui Ueyama       .Cases("*", "/", 5)
4112ec34544SRui Ueyama       .Cases("+", "-", 4)
4122ec34544SRui Ueyama       .Cases("<<", ">>", 3)
4132ec34544SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
4142ec34544SRui Ueyama       .Cases("&", "|", 1)
4152ec34544SRui Ueyama       .Default(-1);
4162ec34544SRui Ueyama }
4172ec34544SRui Ueyama 
4182ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4192ec34544SRui Ueyama   std::vector<StringRef> V;
4202ec34544SRui Ueyama   while (!Error && !consume(")"))
4212ec34544SRui Ueyama     V.push_back(next());
4222ec34544SRui Ueyama   return StringMatcher(V);
4232ec34544SRui Ueyama }
4242ec34544SRui Ueyama 
4252ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
4262ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
4272ec34544SRui Ueyama     return SortSectionPolicy::Name;
4282ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
4292ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
4302ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
4312ec34544SRui Ueyama     return SortSectionPolicy::Priority;
4322ec34544SRui Ueyama   if (consume("SORT_NONE"))
4332ec34544SRui Ueyama     return SortSectionPolicy::None;
4342ec34544SRui Ueyama   return SortSectionPolicy::Default;
4352ec34544SRui Ueyama }
4362ec34544SRui Ueyama 
43703fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
43803fc8d1eSRui Ueyama //
43903fc8d1eSRui Ueyama // <contents> ::= <elem>*
44003fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
44103fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
44203fc8d1eSRui Ueyama //
44303fc8d1eSRui Ueyama // For example,
44403fc8d1eSRui Ueyama //
44503fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
44603fc8d1eSRui Ueyama //
44703fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
44803fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
44903fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
4502ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
4512ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
4522ec34544SRui Ueyama   while (!Error && peek() != ")") {
4532ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
4542ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
4552ec34544SRui Ueyama       expect("(");
4562ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
4572ec34544SRui Ueyama     }
4582ec34544SRui Ueyama 
4592ec34544SRui Ueyama     std::vector<StringRef> V;
4602ec34544SRui Ueyama     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
4612ec34544SRui Ueyama       V.push_back(next());
4622ec34544SRui Ueyama 
4632ec34544SRui Ueyama     if (!V.empty())
4642ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
4652ec34544SRui Ueyama     else
4662ec34544SRui Ueyama       setError("section pattern is expected");
4672ec34544SRui Ueyama   }
4682ec34544SRui Ueyama   return Ret;
4692ec34544SRui Ueyama }
4702ec34544SRui Ueyama 
4712ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
4722ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
4732ec34544SRui Ueyama //
4742ec34544SRui Ueyama // <patterns> ::= <section-list>
4752ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
4762ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
4772ec34544SRui Ueyama //
4782ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
4792ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
4802ec34544SRui Ueyama //
4812ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
4822ec34544SRui Ueyama InputSectionDescription *
4832ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
4842ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
4852ec34544SRui Ueyama   expect("(");
4862ec34544SRui Ueyama 
4872ec34544SRui Ueyama   while (!Error && !consume(")")) {
4882ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
4892ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
4902ec34544SRui Ueyama     std::vector<SectionPattern> V;
4912ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
4922ec34544SRui Ueyama       expect("(");
4932ec34544SRui Ueyama       Inner = readSortKind();
4942ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
4952ec34544SRui Ueyama         expect("(");
4962ec34544SRui Ueyama         V = readInputSectionsList();
4972ec34544SRui Ueyama         expect(")");
4982ec34544SRui Ueyama       } else {
4992ec34544SRui Ueyama         V = readInputSectionsList();
5002ec34544SRui Ueyama       }
5012ec34544SRui Ueyama       expect(")");
5022ec34544SRui Ueyama     } else {
5032ec34544SRui Ueyama       V = readInputSectionsList();
5042ec34544SRui Ueyama     }
5052ec34544SRui Ueyama 
5062ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5072ec34544SRui Ueyama       Pat.SortInner = Inner;
5082ec34544SRui Ueyama       Pat.SortOuter = Outer;
5092ec34544SRui Ueyama     }
5102ec34544SRui Ueyama 
5112ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5122ec34544SRui Ueyama   }
5132ec34544SRui Ueyama   return Cmd;
5142ec34544SRui Ueyama }
5152ec34544SRui Ueyama 
5162ec34544SRui Ueyama InputSectionDescription *
5172ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5182ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5192ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5202ec34544SRui Ueyama   if (Tok == "KEEP") {
5212ec34544SRui Ueyama     expect("(");
5222ec34544SRui Ueyama     StringRef FilePattern = next();
5232ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5242ec34544SRui Ueyama     expect(")");
5252ec34544SRui Ueyama     Script->Opt.KeptSections.push_back(Cmd);
5262ec34544SRui Ueyama     return Cmd;
5272ec34544SRui Ueyama   }
5282ec34544SRui Ueyama   return readInputSectionRules(Tok);
5292ec34544SRui Ueyama }
5302ec34544SRui Ueyama 
5312ec34544SRui Ueyama void ScriptParser::readSort() {
5322ec34544SRui Ueyama   expect("(");
5332ec34544SRui Ueyama   expect("CONSTRUCTORS");
5342ec34544SRui Ueyama   expect(")");
5352ec34544SRui Ueyama }
5362ec34544SRui Ueyama 
53723af89ccSRui Ueyama AssertCommand *ScriptParser::readAssert() {
53823af89ccSRui Ueyama   return make<AssertCommand>(readAssertExpr());
53923af89ccSRui Ueyama }
54023af89ccSRui Ueyama 
54123af89ccSRui Ueyama Expr ScriptParser::readAssertExpr() {
5422ec34544SRui Ueyama   expect("(");
5432ec34544SRui Ueyama   Expr E = readExpr();
5442ec34544SRui Ueyama   expect(",");
5452ec34544SRui Ueyama   StringRef Msg = unquote(next());
5462ec34544SRui Ueyama   expect(")");
547b579c439SRui Ueyama 
5482ec34544SRui Ueyama   return [=] {
5492ec34544SRui Ueyama     if (!E().getValue())
5502ec34544SRui Ueyama       error(Msg);
5512ec34544SRui Ueyama     return Script->getDot();
5522ec34544SRui Ueyama   };
5532ec34544SRui Ueyama }
5542ec34544SRui Ueyama 
5552ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
5562ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
5572ec34544SRui Ueyama // what GNU linkers do.
5582ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
5592ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
5602ec34544SRui Ueyama   expect("(");
5618acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
5622ec34544SRui Ueyama   expect(")");
5632ec34544SRui Ueyama   return V;
5642ec34544SRui Ueyama }
5652ec34544SRui Ueyama 
5662ec34544SRui Ueyama OutputSectionCommand *
5672ec34544SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
56805c4f67cSRafael Espindola   OutputSectionCommand *Cmd =
56905c4f67cSRafael Espindola       Script->createOutputSectionCommand(OutSec, getCurrentLocation());
5702ec34544SRui Ueyama 
5712ec34544SRui Ueyama   // Read an address expression.
572b579c439SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
5732ec34544SRui Ueyama   if (peek() != ":")
5742ec34544SRui Ueyama     Cmd->AddrExpr = readExpr();
5752ec34544SRui Ueyama 
5762ec34544SRui Ueyama   expect(":");
5772ec34544SRui Ueyama 
5782ec34544SRui Ueyama   if (consume("AT"))
5792ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
5802ec34544SRui Ueyama   if (consume("ALIGN"))
5812ec34544SRui Ueyama     Cmd->AlignExpr = readParenExpr();
5822ec34544SRui Ueyama   if (consume("SUBALIGN"))
5832ec34544SRui Ueyama     Cmd->SubalignExpr = readParenExpr();
5842ec34544SRui Ueyama 
5852ec34544SRui Ueyama   // Parse constraints.
5862ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
5872ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
5882ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
5892ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
5902ec34544SRui Ueyama   expect("{");
5912ec34544SRui Ueyama 
5922ec34544SRui Ueyama   while (!Error && !consume("}")) {
5932ec34544SRui Ueyama     StringRef Tok = next();
5942ec34544SRui Ueyama     if (Tok == ";") {
5952ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
596b579c439SRui Ueyama     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
597b579c439SRui Ueyama       Cmd->Commands.push_back(Assign);
5982ec34544SRui Ueyama     } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
5992ec34544SRui Ueyama       Cmd->Commands.push_back(Data);
6002ec34544SRui Ueyama     } else if (Tok == "ASSERT") {
60123af89ccSRui Ueyama       Cmd->Commands.push_back(readAssert());
6022ec34544SRui Ueyama       expect(";");
6032ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
6042ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
6052ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
6062ec34544SRui Ueyama       // For ELF, we should ignore.
6072ec34544SRui Ueyama     } else if (Tok == "FILL") {
6082ec34544SRui Ueyama       Cmd->Filler = readFill();
6092ec34544SRui Ueyama     } else if (Tok == "SORT") {
6102ec34544SRui Ueyama       readSort();
6112ec34544SRui Ueyama     } else if (peek() == "(") {
6122ec34544SRui Ueyama       Cmd->Commands.push_back(readInputSectionDescription(Tok));
6132ec34544SRui Ueyama     } else {
6142ec34544SRui Ueyama       setError("unknown command " + Tok);
6152ec34544SRui Ueyama     }
6162ec34544SRui Ueyama   }
6172ec34544SRui Ueyama 
6182ec34544SRui Ueyama   if (consume(">"))
6192ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
6202ec34544SRui Ueyama 
6212ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
6222ec34544SRui Ueyama 
6232ec34544SRui Ueyama   if (consume("="))
6248acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
6252ec34544SRui Ueyama   else if (peek().startswith("="))
6268acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
6272ec34544SRui Ueyama 
6282ec34544SRui Ueyama   // Consume optional comma following output section command.
6292ec34544SRui Ueyama   consume(",");
6302ec34544SRui Ueyama 
6312ec34544SRui Ueyama   return Cmd;
6322ec34544SRui Ueyama }
6332ec34544SRui Ueyama 
6348acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
6358acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
6362ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
6372ec34544SRui Ueyama //
6388acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
6398acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
6408acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
6418acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
642b58079d4SRui Ueyama   uint32_t V = 0;
643ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
6442ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
645b58079d4SRui Ueyama 
646b58079d4SRui Ueyama   uint32_t Buf;
647b58079d4SRui Ueyama   write32be(&Buf, V);
648b58079d4SRui Ueyama   return Buf;
6492ec34544SRui Ueyama }
6502ec34544SRui Ueyama 
6512ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
6522ec34544SRui Ueyama   expect("(");
6532ec34544SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
6542ec34544SRui Ueyama   Cmd->Provide = Provide;
6552ec34544SRui Ueyama   Cmd->Hidden = Hidden;
6562ec34544SRui Ueyama   expect(")");
6572ec34544SRui Ueyama   expect(";");
6582ec34544SRui Ueyama   return Cmd;
6592ec34544SRui Ueyama }
6602ec34544SRui Ueyama 
6612ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
6622ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
6632ec34544SRui Ueyama   if (peek() == "=" || peek() == "+=") {
6642ec34544SRui Ueyama     Cmd = readAssignment(Tok);
6652ec34544SRui Ueyama     expect(";");
6662ec34544SRui Ueyama   } else if (Tok == "PROVIDE") {
6672ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
6682ec34544SRui Ueyama   } else if (Tok == "HIDDEN") {
6692ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
6702ec34544SRui Ueyama   } else if (Tok == "PROVIDE_HIDDEN") {
6712ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
6722ec34544SRui Ueyama   }
6732ec34544SRui Ueyama   return Cmd;
6742ec34544SRui Ueyama }
6752ec34544SRui Ueyama 
6762ec34544SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
6772ec34544SRui Ueyama   StringRef Op = next();
6782ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
6792ec34544SRui Ueyama   Expr E = readExpr();
6802ec34544SRui Ueyama   if (Op == "+=") {
6812ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
6822ec34544SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
6832ec34544SRui Ueyama   }
6842ec34544SRui Ueyama   return make<SymbolAssignment>(Name, E, getCurrentLocation());
6852ec34544SRui Ueyama }
6862ec34544SRui Ueyama 
6872ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
6882ec34544SRui Ueyama // script expression.
6892ec34544SRui Ueyama Expr ScriptParser::readExpr() {
6902ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
6912ec34544SRui Ueyama   // they apply different tokenization rules.
6922ec34544SRui Ueyama   bool Orig = InExpr;
6932ec34544SRui Ueyama   InExpr = true;
6942ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
6952ec34544SRui Ueyama   InExpr = Orig;
6962ec34544SRui Ueyama   return E;
6972ec34544SRui Ueyama }
6982ec34544SRui Ueyama 
6992ec34544SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
7002ec34544SRui Ueyama   if (Op == "+")
7012ec34544SRui Ueyama     return [=] { return add(L(), R()); };
7022ec34544SRui Ueyama   if (Op == "-")
7032ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
704b579c439SRui Ueyama   if (Op == "*")
705b579c439SRui Ueyama     return [=] { return mul(L(), R()); };
706b579c439SRui Ueyama   if (Op == "/")
707b579c439SRui Ueyama     return [=] { return div(L(), R()); };
7082ec34544SRui Ueyama   if (Op == "<<")
7097e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
7102ec34544SRui Ueyama   if (Op == ">>")
7117e915511SRui Ueyama     return [=] { return L().getValue() >> R().getValue(); };
7122ec34544SRui Ueyama   if (Op == "<")
7132ec34544SRui Ueyama     return [=] { return L().getValue() < R().getValue(); };
7142ec34544SRui Ueyama   if (Op == ">")
7152ec34544SRui Ueyama     return [=] { return L().getValue() > R().getValue(); };
7162ec34544SRui Ueyama   if (Op == ">=")
7172ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
7182ec34544SRui Ueyama   if (Op == "<=")
7192ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
7202ec34544SRui Ueyama   if (Op == "==")
7212ec34544SRui Ueyama     return [=] { return L().getValue() == R().getValue(); };
7222ec34544SRui Ueyama   if (Op == "!=")
7232ec34544SRui Ueyama     return [=] { return L().getValue() != R().getValue(); };
7242ec34544SRui Ueyama   if (Op == "&")
7252ec34544SRui Ueyama     return [=] { return bitAnd(L(), R()); };
7262ec34544SRui Ueyama   if (Op == "|")
7272ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
7282ec34544SRui Ueyama   llvm_unreachable("invalid operator");
7292ec34544SRui Ueyama }
7302ec34544SRui Ueyama 
7312ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
7322ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
7332ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
7342ec34544SRui Ueyama   while (!atEOF() && !Error) {
7352ec34544SRui Ueyama     // Read an operator and an expression.
7362ec34544SRui Ueyama     if (consume("?"))
7372ec34544SRui Ueyama       return readTernary(Lhs);
7382ec34544SRui Ueyama     StringRef Op1 = peek();
7392ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
7402ec34544SRui Ueyama       break;
7412ec34544SRui Ueyama     skip();
7422ec34544SRui Ueyama     Expr Rhs = readPrimary();
7432ec34544SRui Ueyama 
7442ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
7452ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
7462ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
7472ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
7482ec34544SRui Ueyama     while (!atEOF()) {
7492ec34544SRui Ueyama       StringRef Op2 = peek();
7502ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
7512ec34544SRui Ueyama         break;
7522ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
7532ec34544SRui Ueyama     }
7542ec34544SRui Ueyama 
7552ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
7562ec34544SRui Ueyama   }
7572ec34544SRui Ueyama   return Lhs;
7582ec34544SRui Ueyama }
7592ec34544SRui Ueyama 
7602ec34544SRui Ueyama uint64_t static getConstant(StringRef S) {
7612ec34544SRui Ueyama   if (S == "COMMONPAGESIZE")
7622ec34544SRui Ueyama     return Target->PageSize;
7632ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
7642ec34544SRui Ueyama     return Config->MaxPageSize;
7652ec34544SRui Ueyama   error("unknown constant: " + S);
7662ec34544SRui Ueyama   return 0;
7672ec34544SRui Ueyama }
7682ec34544SRui Ueyama 
7695c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
7705c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
7715c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
7725c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
7732ec34544SRui Ueyama   // Negative number
7742ec34544SRui Ueyama   if (Tok.startswith("-")) {
7755c65088fSRui Ueyama     if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
7765c65088fSRui Ueyama       return -*Val;
7775c65088fSRui Ueyama     return None;
7782ec34544SRui Ueyama   }
7792ec34544SRui Ueyama 
7802ec34544SRui Ueyama   // Hexadecimal
7815c65088fSRui Ueyama   uint64_t Val;
782ab94768cSGeorge Rimar   if (Tok.startswith_lower("0x") && to_integer(Tok.substr(2), Val, 16))
7835c65088fSRui Ueyama     return Val;
784ab94768cSGeorge Rimar   if (Tok.endswith_lower("H") && to_integer(Tok.drop_back(), Val, 16))
7855c65088fSRui Ueyama     return Val;
7862ec34544SRui Ueyama 
7872ec34544SRui Ueyama   // Decimal
7882ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
789ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
7905c65088fSRui Ueyama       return None;
7915c65088fSRui Ueyama     return Val * 1024;
7922ec34544SRui Ueyama   }
7935c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
794ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
7955c65088fSRui Ueyama       return None;
7965c65088fSRui Ueyama     return Val * 1024 * 1024;
7975c65088fSRui Ueyama   }
798ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
7995c65088fSRui Ueyama     return None;
8005c65088fSRui Ueyama   return Val;
8012ec34544SRui Ueyama }
8022ec34544SRui Ueyama 
8032ec34544SRui Ueyama BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
804b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
8052ec34544SRui Ueyama                  .Case("BYTE", 1)
8062ec34544SRui Ueyama                  .Case("SHORT", 2)
8072ec34544SRui Ueyama                  .Case("LONG", 4)
8082ec34544SRui Ueyama                  .Case("QUAD", 8)
8092ec34544SRui Ueyama                  .Default(-1);
8102ec34544SRui Ueyama   if (Size == -1)
8112ec34544SRui Ueyama     return nullptr;
8122ec34544SRui Ueyama 
8132ec34544SRui Ueyama   return make<BytesDataCommand>(readParenExpr(), Size);
8142ec34544SRui Ueyama }
8152ec34544SRui Ueyama 
8162ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
8172ec34544SRui Ueyama   expect("(");
8182ec34544SRui Ueyama   StringRef Tok = next();
8192ec34544SRui Ueyama   expect(")");
8202ec34544SRui Ueyama   return Tok;
8212ec34544SRui Ueyama }
8222ec34544SRui Ueyama 
82305c4f67cSRafael Espindola OutputSection *ScriptParser::checkSection(OutputSectionCommand *Cmd,
82405c4f67cSRafael Espindola                                           StringRef Location) {
82505c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
82605c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
82705c4f67cSRafael Espindola   if (Cmd->Sec)
82805c4f67cSRafael Espindola     return Cmd->Sec;
82905c4f67cSRafael Espindola   static OutputSection Dummy("", 0, 0);
83005c4f67cSRafael Espindola   return &Dummy;
83105c4f67cSRafael Espindola }
83205c4f67cSRafael Espindola 
8332ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
8342ec34544SRui Ueyama   if (peek() == "(")
8352ec34544SRui Ueyama     return readParenExpr();
8362ec34544SRui Ueyama 
8375c65088fSRui Ueyama   if (consume("~")) {
8382ec34544SRui Ueyama     Expr E = readPrimary();
839b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
8402ec34544SRui Ueyama   }
8415c65088fSRui Ueyama   if (consume("-")) {
8422ec34544SRui Ueyama     Expr E = readPrimary();
843b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
8442ec34544SRui Ueyama   }
8452ec34544SRui Ueyama 
8465c65088fSRui Ueyama   StringRef Tok = next();
8475c65088fSRui Ueyama   std::string Location = getCurrentLocation();
8485c65088fSRui Ueyama 
8492ec34544SRui Ueyama   // Built-in functions are parsed here.
8502ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
8512ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
8522ec34544SRui Ueyama     Expr Inner = readParenExpr();
8532ec34544SRui Ueyama     return [=] {
8542ec34544SRui Ueyama       ExprValue I = Inner();
8552ec34544SRui Ueyama       I.ForceAbsolute = true;
8562ec34544SRui Ueyama       return I;
8572ec34544SRui Ueyama     };
8582ec34544SRui Ueyama   }
8592ec34544SRui Ueyama   if (Tok == "ADDR") {
8602ec34544SRui Ueyama     StringRef Name = readParenLiteral();
86105c4f67cSRafael Espindola     OutputSectionCommand *Cmd = Script->getOrCreateOutputSectionCommand(Name);
86205c4f67cSRafael Espindola     return [=]() -> ExprValue { return {checkSection(Cmd, Location), 0}; };
8632ec34544SRui Ueyama   }
8642ec34544SRui Ueyama   if (Tok == "ALIGN") {
8652ec34544SRui Ueyama     expect("(");
8662ec34544SRui Ueyama     Expr E = readExpr();
867b579c439SRui Ueyama     if (consume(")"))
868b579c439SRui Ueyama       return [=] { return alignTo(Script->getDot(), E().getValue()); };
869b579c439SRui Ueyama     expect(",");
8702ec34544SRui Ueyama     Expr E2 = readExpr();
8712ec34544SRui Ueyama     expect(")");
8723c6de1a6SPetr Hosek     return [=] {
8733c6de1a6SPetr Hosek       ExprValue V = E();
8743c6de1a6SPetr Hosek       V.Alignment = E2().getValue();
8753c6de1a6SPetr Hosek       return V;
8763c6de1a6SPetr Hosek     };
8772ec34544SRui Ueyama   }
8782ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
8792ec34544SRui Ueyama     StringRef Name = readParenLiteral();
88005c4f67cSRafael Espindola     OutputSectionCommand *Cmd = Script->getOrCreateOutputSectionCommand(Name);
88105c4f67cSRafael Espindola     return [=] { return checkSection(Cmd, Location)->Alignment; };
8822ec34544SRui Ueyama   }
8832ec34544SRui Ueyama   if (Tok == "ASSERT")
88423af89ccSRui Ueyama     return readAssertExpr();
8852ec34544SRui Ueyama   if (Tok == "CONSTANT") {
8862ec34544SRui Ueyama     StringRef Name = readParenLiteral();
8872ec34544SRui Ueyama     return [=] { return getConstant(Name); };
8882ec34544SRui Ueyama   }
8892ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
8902ec34544SRui Ueyama     expect("(");
8912ec34544SRui Ueyama     Expr E = readExpr();
8922ec34544SRui Ueyama     expect(",");
8932ec34544SRui Ueyama     readExpr();
8942ec34544SRui Ueyama     expect(")");
8952ec34544SRui Ueyama     return [=] { return alignTo(Script->getDot(), E().getValue()); };
8962ec34544SRui Ueyama   }
8972ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
8982ec34544SRui Ueyama     expect("(");
8992ec34544SRui Ueyama     expect(".");
9002ec34544SRui Ueyama     expect(")");
9012ec34544SRui Ueyama     return [] { return Script->getDot(); };
9022ec34544SRui Ueyama   }
9032ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
9042ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
9052ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
9062ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
9072ec34544SRui Ueyama     expect("(");
9082ec34544SRui Ueyama     readExpr();
9092ec34544SRui Ueyama     expect(",");
9102ec34544SRui Ueyama     readExpr();
9112ec34544SRui Ueyama     expect(")");
9122ec34544SRui Ueyama     return [] { return alignTo(Script->getDot(), Target->PageSize); };
9132ec34544SRui Ueyama   }
9142ec34544SRui Ueyama   if (Tok == "DEFINED") {
9152ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9162ec34544SRui Ueyama     return [=] { return Script->isDefined(Name) ? 1 : 0; };
9172ec34544SRui Ueyama   }
91891b95b61SRui Ueyama   if (Tok == "LENGTH") {
91991b95b61SRui Ueyama     StringRef Name = readParenLiteral();
92091b95b61SRui Ueyama     if (Script->Opt.MemoryRegions.count(Name) == 0)
92191b95b61SRui Ueyama       setError("memory region not defined: " + Name);
92291b95b61SRui Ueyama     return [=] { return Script->Opt.MemoryRegions[Name].Length; };
92391b95b61SRui Ueyama   }
9242ec34544SRui Ueyama   if (Tok == "LOADADDR") {
9252ec34544SRui Ueyama     StringRef Name = readParenLiteral();
92605c4f67cSRafael Espindola     OutputSectionCommand *Cmd = Script->getOrCreateOutputSectionCommand(Name);
92705c4f67cSRafael Espindola     return [=] { return checkSection(Cmd, Location)->getLMA(); };
9282ec34544SRui Ueyama   }
92991b95b61SRui Ueyama   if (Tok == "ORIGIN") {
93091b95b61SRui Ueyama     StringRef Name = readParenLiteral();
93191b95b61SRui Ueyama     if (Script->Opt.MemoryRegions.count(Name) == 0)
93291b95b61SRui Ueyama       setError("memory region not defined: " + Name);
93391b95b61SRui Ueyama     return [=] { return Script->Opt.MemoryRegions[Name].Origin; };
93491b95b61SRui Ueyama   }
9352ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
9362ec34544SRui Ueyama     expect("(");
9372ec34544SRui Ueyama     skip();
9382ec34544SRui Ueyama     expect(",");
9392ec34544SRui Ueyama     Expr E = readExpr();
9402ec34544SRui Ueyama     expect(")");
9412ec34544SRui Ueyama     return [=] { return E(); };
9422ec34544SRui Ueyama   }
9432ec34544SRui Ueyama   if (Tok == "SIZEOF") {
9442ec34544SRui Ueyama     StringRef Name = readParenLiteral();
94505c4f67cSRafael Espindola     OutputSectionCommand *Cmd = Script->getOrCreateOutputSectionCommand(Name);
94605c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
94705c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
94805c4f67cSRafael Espindola     // be empty.
94905c4f67cSRafael Espindola     return [=] { return Cmd->Sec ? Cmd->Sec->Size : 0; };
9502ec34544SRui Ueyama   }
9512ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
9522ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
9532ec34544SRui Ueyama 
9544eb2eccbSRui Ueyama   // Tok is the dot.
9554eb2eccbSRui Ueyama   if (Tok == ".")
9564eb2eccbSRui Ueyama     return [=] { return Script->getSymbolValue(Location, Tok); };
9574eb2eccbSRui Ueyama 
9582ec34544SRui Ueyama   // Tok is a literal number.
9595c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
9605c65088fSRui Ueyama     return [=] { return *Val; };
9612ec34544SRui Ueyama 
9622ec34544SRui Ueyama   // Tok is a symbol name.
9632ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
9642ec34544SRui Ueyama     setError("malformed number: " + Tok);
9654eb2eccbSRui Ueyama   Script->Opt.ReferencedSymbols.push_back(Tok);
9662ec34544SRui Ueyama   return [=] { return Script->getSymbolValue(Location, Tok); };
9672ec34544SRui Ueyama }
9682ec34544SRui Ueyama 
9692ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
9702ec34544SRui Ueyama   Expr L = readExpr();
9712ec34544SRui Ueyama   expect(":");
9722ec34544SRui Ueyama   Expr R = readExpr();
9732ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
9742ec34544SRui Ueyama }
9752ec34544SRui Ueyama 
9762ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
9772ec34544SRui Ueyama   expect("(");
9782ec34544SRui Ueyama   Expr E = readExpr();
9792ec34544SRui Ueyama   expect(")");
9802ec34544SRui Ueyama   return E;
9812ec34544SRui Ueyama }
9822ec34544SRui Ueyama 
9832ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
9842ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
9852ec34544SRui Ueyama   while (!Error && peek().startswith(":")) {
9862ec34544SRui Ueyama     StringRef Tok = next();
9872ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
9882ec34544SRui Ueyama   }
9892ec34544SRui Ueyama   return Phdrs;
9902ec34544SRui Ueyama }
9912ec34544SRui Ueyama 
9922ec34544SRui Ueyama // Read a program header type name. The next token must be a
9932ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
9942ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
9952ec34544SRui Ueyama   StringRef Tok = next();
9965c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
9975c65088fSRui Ueyama     return *Val;
9982ec34544SRui Ueyama 
9992ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
10002ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
10012ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
10022ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
10032ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
10042ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
10052ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
10062ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
10072ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
10082ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
10092ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
10102ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
10112ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
10122ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
10132ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
10142ec34544SRui Ueyama                      .Default(-1);
10152ec34544SRui Ueyama 
10162ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
10172ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
10182ec34544SRui Ueyama     return PT_NULL;
10192ec34544SRui Ueyama   }
10202ec34544SRui Ueyama   return Ret;
10212ec34544SRui Ueyama }
10222ec34544SRui Ueyama 
10232ec34544SRui Ueyama // Reads an anonymous version declaration.
10242ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
10252ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
10262ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
10272ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
10282ec34544SRui Ueyama 
10292ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
10302ec34544SRui Ueyama     if (V.Name == "*")
10312ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
10322ec34544SRui Ueyama     else
10332ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
10342ec34544SRui Ueyama   }
10352ec34544SRui Ueyama 
10362ec34544SRui Ueyama   for (SymbolVersion V : Globals)
10372ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
10382ec34544SRui Ueyama 
10392ec34544SRui Ueyama   expect(";");
10402ec34544SRui Ueyama }
10412ec34544SRui Ueyama 
10422ec34544SRui Ueyama // Reads a non-anonymous version definition,
10432ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
10442ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
10452ec34544SRui Ueyama   // Read a symbol list.
10462ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
10472ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
10482ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
10492ec34544SRui Ueyama 
10502ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
10512ec34544SRui Ueyama     if (V.Name == "*")
10522ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
10532ec34544SRui Ueyama     else
10542ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
10552ec34544SRui Ueyama   }
10562ec34544SRui Ueyama 
10572ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
10582ec34544SRui Ueyama   VersionDefinition Ver;
10592ec34544SRui Ueyama   Ver.Name = VerStr;
10602ec34544SRui Ueyama   Ver.Globals = Globals;
10612ec34544SRui Ueyama 
10622ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
10632ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
10642ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
10652ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
10662ec34544SRui Ueyama 
10672ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
10682ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
10692ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
10702ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
10712ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
10722ec34544SRui Ueyama   if (peek() != ";")
10732ec34544SRui Ueyama     skip();
10742ec34544SRui Ueyama   expect(";");
10752ec34544SRui Ueyama }
10762ec34544SRui Ueyama 
10772ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
10782ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
10792ec34544SRui Ueyama ScriptParser::readSymbols() {
10802ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
10812ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
10822ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
10832ec34544SRui Ueyama 
10842ec34544SRui Ueyama   while (!Error) {
10852ec34544SRui Ueyama     if (consume("}"))
10862ec34544SRui Ueyama       break;
10872ec34544SRui Ueyama     if (consumeLabel("local")) {
10882ec34544SRui Ueyama       V = &Locals;
10892ec34544SRui Ueyama       continue;
10902ec34544SRui Ueyama     }
10912ec34544SRui Ueyama     if (consumeLabel("global")) {
10922ec34544SRui Ueyama       V = &Globals;
10932ec34544SRui Ueyama       continue;
10942ec34544SRui Ueyama     }
10952ec34544SRui Ueyama 
10962ec34544SRui Ueyama     if (consume("extern")) {
10972ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
10982ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
10992ec34544SRui Ueyama     } else {
11002ec34544SRui Ueyama       StringRef Tok = next();
11012ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
11022ec34544SRui Ueyama     }
11032ec34544SRui Ueyama     expect(";");
11042ec34544SRui Ueyama   }
11052ec34544SRui Ueyama   return {Locals, Globals};
11062ec34544SRui Ueyama }
11072ec34544SRui Ueyama 
11082ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
11092ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
11102ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
11112ec34544SRui Ueyama   StringRef Tok = next();
11122ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
11132ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
11142ec34544SRui Ueyama     setError("Unknown language");
11152ec34544SRui Ueyama   expect("{");
11162ec34544SRui Ueyama 
11172ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
11182ec34544SRui Ueyama   while (!Error && peek() != "}") {
11192ec34544SRui Ueyama     StringRef Tok = next();
11202ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
11212ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
11222ec34544SRui Ueyama     expect(";");
11232ec34544SRui Ueyama   }
11242ec34544SRui Ueyama 
11252ec34544SRui Ueyama   expect("}");
11262ec34544SRui Ueyama   return Ret;
11272ec34544SRui Ueyama }
11282ec34544SRui Ueyama 
11292ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
11302ec34544SRui Ueyama                                             StringRef S3) {
1131b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
11322ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
11332ec34544SRui Ueyama     return 0;
11342ec34544SRui Ueyama   }
11352ec34544SRui Ueyama   expect("=");
1136040af7deSRui Ueyama   return readExpr()().getValue();
11372ec34544SRui Ueyama }
11382ec34544SRui Ueyama 
11392ec34544SRui Ueyama // Parse the MEMORY command as specified in:
11402ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
11412ec34544SRui Ueyama //
11422ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
11432ec34544SRui Ueyama void ScriptParser::readMemory() {
11442ec34544SRui Ueyama   expect("{");
11452ec34544SRui Ueyama   while (!Error && !consume("}")) {
11462ec34544SRui Ueyama     StringRef Name = next();
11472ec34544SRui Ueyama 
11482ec34544SRui Ueyama     uint32_t Flags = 0;
11492ec34544SRui Ueyama     uint32_t NegFlags = 0;
11502ec34544SRui Ueyama     if (consume("(")) {
11512ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
11522ec34544SRui Ueyama       expect(")");
11532ec34544SRui Ueyama     }
11542ec34544SRui Ueyama     expect(":");
11552ec34544SRui Ueyama 
11562ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
11572ec34544SRui Ueyama     expect(",");
11582ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
11592ec34544SRui Ueyama 
11602ec34544SRui Ueyama     // Add the memory region to the region map (if it doesn't already exist).
11612ec34544SRui Ueyama     auto It = Script->Opt.MemoryRegions.find(Name);
11622ec34544SRui Ueyama     if (It != Script->Opt.MemoryRegions.end())
11632ec34544SRui Ueyama       setError("region '" + Name + "' already defined");
11642ec34544SRui Ueyama     else
11652ec34544SRui Ueyama       Script->Opt.MemoryRegions[Name] = {Name,   Origin, Length,
11662ec34544SRui Ueyama                                          Origin, Flags,  NegFlags};
11672ec34544SRui Ueyama   }
11682ec34544SRui Ueyama }
11692ec34544SRui Ueyama 
11702ec34544SRui Ueyama // This function parses the attributes used to match against section
11712ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
11722ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
11732ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
11742ec34544SRui Ueyama   uint32_t Flags = 0;
11752ec34544SRui Ueyama   uint32_t NegFlags = 0;
11762ec34544SRui Ueyama   bool Invert = false;
11772ec34544SRui Ueyama 
11782ec34544SRui Ueyama   for (char C : next().lower()) {
11792ec34544SRui Ueyama     uint32_t Flag = 0;
11802ec34544SRui Ueyama     if (C == '!')
11812ec34544SRui Ueyama       Invert = !Invert;
11822ec34544SRui Ueyama     else if (C == 'w')
11832ec34544SRui Ueyama       Flag = SHF_WRITE;
11842ec34544SRui Ueyama     else if (C == 'x')
11852ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
11862ec34544SRui Ueyama     else if (C == 'a')
11872ec34544SRui Ueyama       Flag = SHF_ALLOC;
11882ec34544SRui Ueyama     else if (C != 'r')
11892ec34544SRui Ueyama       setError("invalid memory region attribute");
11902ec34544SRui Ueyama 
11912ec34544SRui Ueyama     if (Invert)
11922ec34544SRui Ueyama       NegFlags |= Flag;
11932ec34544SRui Ueyama     else
11942ec34544SRui Ueyama       Flags |= Flag;
11952ec34544SRui Ueyama   }
11962ec34544SRui Ueyama   return {Flags, NegFlags};
11972ec34544SRui Ueyama }
11982ec34544SRui Ueyama 
11992ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
12002ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
12012ec34544SRui Ueyama }
12022ec34544SRui Ueyama 
12032ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
12042ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
12052ec34544SRui Ueyama }
12062ec34544SRui Ueyama 
12072ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
12082ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
12092ec34544SRui Ueyama }
1210