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 "OutputSections.h"
212ec34544SRui Ueyama #include "ScriptLexer.h"
222ec34544SRui Ueyama #include "Symbols.h"
232ec34544SRui Ueyama #include "Target.h"
242017d52bSRui Ueyama #include "lld/Common/Memory.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();
568c7e8cceSPetr Hosek   void readDefsym(StringRef Name);
572ec34544SRui Ueyama 
582ec34544SRui Ueyama private:
592ec34544SRui Ueyama   void addFile(StringRef Path);
602ec34544SRui Ueyama 
612ec34544SRui Ueyama   void readAsNeeded();
622ec34544SRui Ueyama   void readEntry();
632ec34544SRui Ueyama   void readExtern();
642ec34544SRui Ueyama   void readGroup();
652ec34544SRui Ueyama   void readInclude();
661d92aa73SRui Ueyama   void readInput();
672ec34544SRui Ueyama   void readMemory();
682ec34544SRui Ueyama   void readOutput();
692ec34544SRui Ueyama   void readOutputArch();
702ec34544SRui Ueyama   void readOutputFormat();
712ec34544SRui Ueyama   void readPhdrs();
725f37541cSGeorge Rimar   void readRegionAlias();
732ec34544SRui Ueyama   void readSearchDir();
742ec34544SRui Ueyama   void readSections();
752ec34544SRui Ueyama   void readVersion();
762ec34544SRui Ueyama   void readVersionScriptCommand();
772ec34544SRui Ueyama 
782ec34544SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
79f0403c60SRui Ueyama   ByteCommand *readByteCommand(StringRef Tok);
802ec34544SRui Ueyama   uint32_t readFill();
818acbf1ccSRui Ueyama   uint32_t parseFill(StringRef Tok);
828c022ca7SRafael Espindola   void readSectionAddressType(OutputSection *Cmd);
838c022ca7SRafael Espindola   OutputSection *readOutputSectionDescription(StringRef OutSec);
842ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
852ec34544SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef Tok);
862ec34544SRui Ueyama   StringMatcher readFilePatterns();
872ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
882ec34544SRui Ueyama   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
892ec34544SRui Ueyama   unsigned readPhdrType();
902ec34544SRui Ueyama   SortSectionPolicy readSortKind();
912ec34544SRui Ueyama   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
922ec34544SRui Ueyama   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
932ec34544SRui Ueyama   void readSort();
9423af89ccSRui Ueyama   AssertCommand *readAssert();
9523af89ccSRui Ueyama   Expr readAssertExpr();
965fb17128SGeorge Rimar   Expr readConstant();
975fb17128SGeorge Rimar   Expr getPageSize();
982ec34544SRui Ueyama 
992ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1002ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1012ec34544SRui Ueyama 
1027b91e213SGeorge Rimar   Expr combine(StringRef Op, Expr L, Expr R);
1032ec34544SRui Ueyama   Expr readExpr();
1042ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1052ec34544SRui Ueyama   StringRef readParenLiteral();
1062ec34544SRui Ueyama   Expr readPrimary();
1072ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1082ec34544SRui Ueyama   Expr readParenExpr();
1092ec34544SRui Ueyama 
1102ec34544SRui Ueyama   // For parsing version script.
1112ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1122ec34544SRui Ueyama   void readAnonymousDeclaration();
1132ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1142ec34544SRui Ueyama 
1152ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1162ec34544SRui Ueyama   readSymbols();
1172ec34544SRui Ueyama 
118fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1192ec34544SRui Ueyama   bool IsUnderSysroot;
1200440be4aSRui Ueyama 
1210440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1220440be4aSRui Ueyama   StringSet<> Seen;
1232ec34544SRui Ueyama };
12496b3fe02SRui Ueyama } // namespace
1252ec34544SRui Ueyama 
1261e77ad14SRui Ueyama static StringRef unquote(StringRef S) {
1271e77ad14SRui Ueyama   if (S.startswith("\""))
1281e77ad14SRui Ueyama     return S.substr(1, S.size() - 2);
1291e77ad14SRui Ueyama   return S;
1301e77ad14SRui Ueyama }
1311e77ad14SRui Ueyama 
1322ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1332ec34544SRui Ueyama   if (Config->Sysroot == "")
1342ec34544SRui Ueyama     return false;
1352ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1362ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1372ec34544SRui Ueyama       return true;
1382ec34544SRui Ueyama   return false;
1392ec34544SRui Ueyama }
1402ec34544SRui Ueyama 
1412ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1422ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1432ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
14423be5e8dSRafael Espindola   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
1452ec34544SRui Ueyama     std::swap(A, B);
1462ec34544SRui Ueyama   if (!B.isAbsolute())
14741c7ab4aSGeorge Rimar     error(A.Loc + ": at least one side of the expression must be absolute");
1482ec34544SRui Ueyama }
1492ec34544SRui Ueyama 
1502ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1512ec34544SRui Ueyama   moveAbsRight(A, B);
152a6acd23cSRafael Espindola   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
1532ec34544SRui Ueyama }
1542ec34544SRui Ueyama 
1552ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
15663a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1579cbb6dd1SRafael Espindola   if (!A.isAbsolute() && !B.isAbsolute())
1589cbb6dd1SRafael Espindola     return A.getValue() - B.getValue();
1594fbe3518SRui Ueyama   return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
1602ec34544SRui Ueyama }
1612ec34544SRui Ueyama 
1622ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1632ec34544SRui Ueyama   moveAbsRight(A, B);
1642ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
16541c7ab4aSGeorge Rimar           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
1662ec34544SRui Ueyama }
1672ec34544SRui Ueyama 
1682ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1692ec34544SRui Ueyama   moveAbsRight(A, B);
1702ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17141c7ab4aSGeorge Rimar           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
1722ec34544SRui Ueyama }
1732ec34544SRui Ueyama 
1742ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1758016bdfdSRafael Espindola   Config->HasDynamicList = true;
1762ec34544SRui Ueyama   expect("{");
177d72d97b3SRafael Espindola   std::vector<SymbolVersion> Locals;
178d72d97b3SRafael Espindola   std::vector<SymbolVersion> Globals;
179d72d97b3SRafael Espindola   std::tie(Locals, Globals) = readSymbols();
180d72d97b3SRafael Espindola   expect(";");
181d72d97b3SRafael Espindola 
182d72d97b3SRafael Espindola   if (!atEOF()) {
1832ec34544SRui Ueyama     setError("EOF expected, but got " + next());
184d72d97b3SRafael Espindola     return;
185d72d97b3SRafael Espindola   }
186d72d97b3SRafael Espindola   if (!Locals.empty()) {
187d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
188d72d97b3SRafael Espindola     return;
189d72d97b3SRafael Espindola   }
190d72d97b3SRafael Espindola 
191d72d97b3SRafael Espindola   for (SymbolVersion V : Globals)
192d72d97b3SRafael Espindola     Config->DynamicList.push_back(V);
1932ec34544SRui Ueyama }
1942ec34544SRui Ueyama 
1952ec34544SRui Ueyama void ScriptParser::readVersionScript() {
1962ec34544SRui Ueyama   readVersionScriptCommand();
1972ec34544SRui Ueyama   if (!atEOF())
1982ec34544SRui Ueyama     setError("EOF expected, but got " + next());
1992ec34544SRui Ueyama }
2002ec34544SRui Ueyama 
2012ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2022ec34544SRui Ueyama   if (consume("{")) {
2032ec34544SRui Ueyama     readAnonymousDeclaration();
2042ec34544SRui Ueyama     return;
2052ec34544SRui Ueyama   }
2062ec34544SRui Ueyama 
207b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2082ec34544SRui Ueyama     StringRef VerStr = next();
2092ec34544SRui Ueyama     if (VerStr == "{") {
2102ec34544SRui Ueyama       setError("anonymous version definition is used in "
2112ec34544SRui Ueyama                "combination with other version definitions");
2122ec34544SRui Ueyama       return;
2132ec34544SRui Ueyama     }
2142ec34544SRui Ueyama     expect("{");
2152ec34544SRui Ueyama     readVersionDeclaration(VerStr);
2162ec34544SRui Ueyama   }
2172ec34544SRui Ueyama }
2182ec34544SRui Ueyama 
2192ec34544SRui Ueyama void ScriptParser::readVersion() {
2202ec34544SRui Ueyama   expect("{");
2212ec34544SRui Ueyama   readVersionScriptCommand();
2222ec34544SRui Ueyama   expect("}");
2232ec34544SRui Ueyama }
2242ec34544SRui Ueyama 
2252ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2262ec34544SRui Ueyama   while (!atEOF()) {
2272ec34544SRui Ueyama     StringRef Tok = next();
2282ec34544SRui Ueyama     if (Tok == ";")
2292ec34544SRui Ueyama       continue;
2302ec34544SRui Ueyama 
2312ec34544SRui Ueyama     if (Tok == "ASSERT") {
2326b394caaSRui Ueyama       Script->SectionCommands.push_back(readAssert());
2332ec34544SRui Ueyama     } else if (Tok == "ENTRY") {
2342ec34544SRui Ueyama       readEntry();
2352ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2362ec34544SRui Ueyama       readExtern();
2371d92aa73SRui Ueyama     } else if (Tok == "GROUP") {
2382ec34544SRui Ueyama       readGroup();
2392ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2402ec34544SRui Ueyama       readInclude();
2411d92aa73SRui Ueyama     } else if (Tok == "INPUT") {
2421d92aa73SRui Ueyama       readInput();
2432ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2442ec34544SRui Ueyama       readMemory();
2452ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2462ec34544SRui Ueyama       readOutput();
2472ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2482ec34544SRui Ueyama       readOutputArch();
2492ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2502ec34544SRui Ueyama       readOutputFormat();
2512ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2522ec34544SRui Ueyama       readPhdrs();
2535f37541cSGeorge Rimar     } else if (Tok == "REGION_ALIAS") {
2545f37541cSGeorge Rimar       readRegionAlias();
2552ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2562ec34544SRui Ueyama       readSearchDir();
2572ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2582ec34544SRui Ueyama       readSections();
2592ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2602ec34544SRui Ueyama       readVersion();
2612ec34544SRui Ueyama     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
2626b394caaSRui Ueyama       Script->SectionCommands.push_back(Cmd);
2632ec34544SRui Ueyama     } else {
2642ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2652ec34544SRui Ueyama     }
2662ec34544SRui Ueyama   }
2672ec34544SRui Ueyama }
2682ec34544SRui Ueyama 
2698c7e8cceSPetr Hosek void ScriptParser::readDefsym(StringRef Name) {
2708c7e8cceSPetr Hosek   Expr E = readExpr();
2718c7e8cceSPetr Hosek   if (!atEOF())
2728c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
273e88b76a9SGeorge Rimar   SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
2748c7e8cceSPetr Hosek   Script->SectionCommands.push_back(Cmd);
2758c7e8cceSPetr Hosek }
2768c7e8cceSPetr Hosek 
2772ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2782ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2792ec34544SRui Ueyama     SmallString<128> PathData;
2802ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2812ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
282a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2832ec34544SRui Ueyama       return;
2842ec34544SRui Ueyama     }
2852ec34544SRui Ueyama   }
2862ec34544SRui Ueyama 
287875ae82bSRui Ueyama   if (S.startswith("/")) {
288a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2892ec34544SRui Ueyama   } else if (S.startswith("=")) {
2902ec34544SRui Ueyama     if (Config->Sysroot.empty())
291a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
2922ec34544SRui Ueyama     else
293a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
294a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
2952ec34544SRui Ueyama   } else if (S.startswith("-l")) {
2962ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
2972ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
298a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2992ec34544SRui Ueyama   } else {
3002ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
301a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
3022ec34544SRui Ueyama     else
3032ec34544SRui Ueyama       setError("unable to find " + S);
3042ec34544SRui Ueyama   }
3052ec34544SRui Ueyama }
3062ec34544SRui Ueyama 
3072ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3082ec34544SRui Ueyama   expect("(");
3092ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
3102ec34544SRui Ueyama   Config->AsNeeded = true;
311b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3122ec34544SRui Ueyama     addFile(unquote(next()));
3132ec34544SRui Ueyama   Config->AsNeeded = Orig;
3142ec34544SRui Ueyama }
3152ec34544SRui Ueyama 
3162ec34544SRui Ueyama void ScriptParser::readEntry() {
3172ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3182ec34544SRui Ueyama   expect("(");
3192ec34544SRui Ueyama   StringRef Tok = next();
3202ec34544SRui Ueyama   if (Config->Entry.empty())
3212ec34544SRui Ueyama     Config->Entry = Tok;
3222ec34544SRui Ueyama   expect(")");
3232ec34544SRui Ueyama }
3242ec34544SRui Ueyama 
3252ec34544SRui Ueyama void ScriptParser::readExtern() {
3262ec34544SRui Ueyama   expect("(");
327b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3282ec34544SRui Ueyama     Config->Undefined.push_back(next());
3292ec34544SRui Ueyama }
3302ec34544SRui Ueyama 
3312ec34544SRui Ueyama void ScriptParser::readGroup() {
3321d92aa73SRui Ueyama   bool Orig = InputFile::IsInGroup;
3331d92aa73SRui Ueyama   InputFile::IsInGroup = true;
3341d92aa73SRui Ueyama   readInput();
3351d92aa73SRui Ueyama   InputFile::IsInGroup = Orig;
336*b72daf00SFangrui Song   if (!Orig)
337*b72daf00SFangrui Song     ++InputFile::NextGroupId;
3382ec34544SRui Ueyama }
3392ec34544SRui Ueyama 
3402ec34544SRui Ueyama void ScriptParser::readInclude() {
3412ec34544SRui Ueyama   StringRef Tok = unquote(next());
3422ec34544SRui Ueyama 
3430440be4aSRui Ueyama   if (!Seen.insert(Tok).second) {
3440440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3450440be4aSRui Ueyama     return;
3460440be4aSRui Ueyama   }
3470440be4aSRui Ueyama 
3481de78471SAlexander Richardson   if (Optional<std::string> Path = searchLinkerScript(Tok)) {
3492ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3502ec34544SRui Ueyama       tokenize(*MB);
3512ec34544SRui Ueyama     return;
3522ec34544SRui Ueyama   }
3531de78471SAlexander Richardson   setError("cannot find linker script " + Tok);
3542ec34544SRui Ueyama }
3552ec34544SRui Ueyama 
3561d92aa73SRui Ueyama void ScriptParser::readInput() {
3571d92aa73SRui Ueyama   expect("(");
3581d92aa73SRui Ueyama   while (!errorCount() && !consume(")")) {
3591d92aa73SRui Ueyama     if (consume("AS_NEEDED"))
3601d92aa73SRui Ueyama       readAsNeeded();
3611d92aa73SRui Ueyama     else
3621d92aa73SRui Ueyama       addFile(unquote(next()));
3631d92aa73SRui Ueyama   }
3641d92aa73SRui Ueyama }
3651d92aa73SRui Ueyama 
3662ec34544SRui Ueyama void ScriptParser::readOutput() {
3672ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3682ec34544SRui Ueyama   expect("(");
3692ec34544SRui Ueyama   StringRef Tok = next();
3702ec34544SRui Ueyama   if (Config->OutputFile.empty())
3712ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3722ec34544SRui Ueyama   expect(")");
3732ec34544SRui Ueyama }
3742ec34544SRui Ueyama 
3752ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3762ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3772ec34544SRui Ueyama   expect("(");
378b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3792ec34544SRui Ueyama     skip();
3802ec34544SRui Ueyama }
3812ec34544SRui Ueyama 
3822ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3832ec34544SRui Ueyama   // Error checking only for now.
3842ec34544SRui Ueyama   expect("(");
3852ec34544SRui Ueyama   skip();
386b579c439SRui Ueyama   if (consume(")"))
3872ec34544SRui Ueyama     return;
388b579c439SRui Ueyama   expect(",");
3892ec34544SRui Ueyama   skip();
3902ec34544SRui Ueyama   expect(",");
3912ec34544SRui Ueyama   skip();
3922ec34544SRui Ueyama   expect(")");
3932ec34544SRui Ueyama }
3942ec34544SRui Ueyama 
3952ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3962ec34544SRui Ueyama   expect("{");
3972ec34544SRui Ueyama 
398b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
3990ae2c24cSRui Ueyama     PhdrsCommand Cmd;
4000ae2c24cSRui Ueyama     Cmd.Name = next();
4010ae2c24cSRui Ueyama     Cmd.Type = readPhdrType();
402b579c439SRui Ueyama 
403b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
404b579c439SRui Ueyama       if (consume("FILEHDR"))
4050ae2c24cSRui Ueyama         Cmd.HasFilehdr = true;
406b579c439SRui Ueyama       else if (consume("PHDRS"))
4070ae2c24cSRui Ueyama         Cmd.HasPhdrs = true;
408b579c439SRui Ueyama       else if (consume("AT"))
4090ae2c24cSRui Ueyama         Cmd.LMAExpr = readParenExpr();
410b579c439SRui Ueyama       else if (consume("FLAGS"))
4110ae2c24cSRui Ueyama         Cmd.Flags = readParenExpr()().getValue();
412b579c439SRui Ueyama       else
413b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
414b579c439SRui Ueyama     }
4150ae2c24cSRui Ueyama 
416ac27de9dSRui Ueyama     Script->PhdrsCommands.push_back(Cmd);
4172ec34544SRui Ueyama   }
4182ec34544SRui Ueyama }
4192ec34544SRui Ueyama 
4205f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4215f37541cSGeorge Rimar   expect("(");
4225f37541cSGeorge Rimar   StringRef Alias = unquote(next());
4235f37541cSGeorge Rimar   expect(",");
4245f37541cSGeorge Rimar   StringRef Name = next();
4255f37541cSGeorge Rimar   expect(")");
4265f37541cSGeorge Rimar 
427ac27de9dSRui Ueyama   if (Script->MemoryRegions.count(Alias))
4285f37541cSGeorge Rimar     setError("redefinition of memory region '" + Alias + "'");
429ac27de9dSRui Ueyama   if (!Script->MemoryRegions.count(Name))
4305f37541cSGeorge Rimar     setError("memory region '" + Name + "' is not defined");
4318c825db2SGeorge Rimar   Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
4325f37541cSGeorge Rimar }
4335f37541cSGeorge Rimar 
4342ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4352ec34544SRui Ueyama   expect("(");
4362ec34544SRui Ueyama   StringRef Tok = next();
4372ec34544SRui Ueyama   if (!Config->Nostdlib)
4382ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
4392ec34544SRui Ueyama   expect(")");
4402ec34544SRui Ueyama }
4412ec34544SRui Ueyama 
4422ec34544SRui Ueyama void ScriptParser::readSections() {
443a323e2a7SRui Ueyama   Script->HasSectionsCommand = true;
444b579c439SRui Ueyama 
4452ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
4462ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
4472ec34544SRui Ueyama   // script. See comment for computeFlags().
4482ec34544SRui Ueyama   Config->SingleRoRx = true;
4492ec34544SRui Ueyama 
4502ec34544SRui Ueyama   expect("{");
4519e2c8a9dSGeorge Rimar   std::vector<BaseCommand *> V;
452b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4532ec34544SRui Ueyama     StringRef Tok = next();
4542ec34544SRui Ueyama     BaseCommand *Cmd = readProvideOrAssignment(Tok);
4552ec34544SRui Ueyama     if (!Cmd) {
4562ec34544SRui Ueyama       if (Tok == "ASSERT")
45723af89ccSRui Ueyama         Cmd = readAssert();
4582ec34544SRui Ueyama       else
4592ec34544SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
4602ec34544SRui Ueyama     }
4619e2c8a9dSGeorge Rimar     V.push_back(Cmd);
4622ec34544SRui Ueyama   }
4639e2c8a9dSGeorge Rimar 
4649e2c8a9dSGeorge Rimar   if (!atEOF() && consume("INSERT")) {
465796684b4SGeorge Rimar     std::vector<BaseCommand *> *Dest = nullptr;
466796684b4SGeorge Rimar     if (consume("AFTER"))
467796684b4SGeorge Rimar       Dest = &Script->InsertAfterCommands[next()];
468796684b4SGeorge Rimar     else if (consume("BEFORE"))
469796684b4SGeorge Rimar       Dest = &Script->InsertBeforeCommands[next()];
470796684b4SGeorge Rimar     else
471796684b4SGeorge Rimar       setError("expected AFTER/BEFORE, but got '" + next() + "'");
472796684b4SGeorge Rimar     if (Dest)
473796684b4SGeorge Rimar       Dest->insert(Dest->end(), V.begin(), V.end());
4749e2c8a9dSGeorge Rimar     return;
4759e2c8a9dSGeorge Rimar   }
4769e2c8a9dSGeorge Rimar 
4779e2c8a9dSGeorge Rimar   Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(),
4789e2c8a9dSGeorge Rimar                                  V.end());
4792ec34544SRui Ueyama }
4802ec34544SRui Ueyama 
4812ec34544SRui Ueyama static int precedence(StringRef Op) {
4822ec34544SRui Ueyama   return StringSwitch<int>(Op)
483aa92fca8SRui Ueyama       .Cases("*", "/", "%", 6)
484aa92fca8SRui Ueyama       .Cases("+", "-", 5)
485aa92fca8SRui Ueyama       .Cases("<<", ">>", 4)
486aa92fca8SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 3)
487aa92fca8SRui Ueyama       .Case("&", 2)
488aa92fca8SRui Ueyama       .Case("|", 1)
4892ec34544SRui Ueyama       .Default(-1);
4902ec34544SRui Ueyama }
4912ec34544SRui Ueyama 
4922ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4932ec34544SRui Ueyama   std::vector<StringRef> V;
494b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4952ec34544SRui Ueyama     V.push_back(next());
4962ec34544SRui Ueyama   return StringMatcher(V);
4972ec34544SRui Ueyama }
4982ec34544SRui Ueyama 
4992ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
5002ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
5012ec34544SRui Ueyama     return SortSectionPolicy::Name;
5022ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
5032ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
5042ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
5052ec34544SRui Ueyama     return SortSectionPolicy::Priority;
5062ec34544SRui Ueyama   if (consume("SORT_NONE"))
5072ec34544SRui Ueyama     return SortSectionPolicy::None;
5082ec34544SRui Ueyama   return SortSectionPolicy::Default;
5092ec34544SRui Ueyama }
5102ec34544SRui Ueyama 
51103fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
51203fc8d1eSRui Ueyama //
51303fc8d1eSRui Ueyama // <contents> ::= <elem>*
51403fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
51503fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
51603fc8d1eSRui Ueyama //
51703fc8d1eSRui Ueyama // For example,
51803fc8d1eSRui Ueyama //
51903fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
52003fc8d1eSRui Ueyama //
52103fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
52203fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
52303fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
5242ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
5252ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
526b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
5272ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
5282ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
5292ec34544SRui Ueyama       expect("(");
5302ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
5312ec34544SRui Ueyama     }
5322ec34544SRui Ueyama 
5332ec34544SRui Ueyama     std::vector<StringRef> V;
534b8a59c8aSBob Haarman     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
5352ec34544SRui Ueyama       V.push_back(next());
5362ec34544SRui Ueyama 
5372ec34544SRui Ueyama     if (!V.empty())
5382ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
5392ec34544SRui Ueyama     else
5402ec34544SRui Ueyama       setError("section pattern is expected");
5412ec34544SRui Ueyama   }
5422ec34544SRui Ueyama   return Ret;
5432ec34544SRui Ueyama }
5442ec34544SRui Ueyama 
5452ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
5462ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
5472ec34544SRui Ueyama //
5482ec34544SRui Ueyama // <patterns> ::= <section-list>
5492ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
5502ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
5512ec34544SRui Ueyama //
5522ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
5532ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
5542ec34544SRui Ueyama //
5552ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
5562ec34544SRui Ueyama InputSectionDescription *
5572ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
5582ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
5592ec34544SRui Ueyama   expect("(");
5602ec34544SRui Ueyama 
561b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
5622ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
5632ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
5642ec34544SRui Ueyama     std::vector<SectionPattern> V;
5652ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
5662ec34544SRui Ueyama       expect("(");
5672ec34544SRui Ueyama       Inner = readSortKind();
5682ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
5692ec34544SRui Ueyama         expect("(");
5702ec34544SRui Ueyama         V = readInputSectionsList();
5712ec34544SRui Ueyama         expect(")");
5722ec34544SRui Ueyama       } else {
5732ec34544SRui Ueyama         V = readInputSectionsList();
5742ec34544SRui Ueyama       }
5752ec34544SRui Ueyama       expect(")");
5762ec34544SRui Ueyama     } else {
5772ec34544SRui Ueyama       V = readInputSectionsList();
5782ec34544SRui Ueyama     }
5792ec34544SRui Ueyama 
5802ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5812ec34544SRui Ueyama       Pat.SortInner = Inner;
5822ec34544SRui Ueyama       Pat.SortOuter = Outer;
5832ec34544SRui Ueyama     }
5842ec34544SRui Ueyama 
5852ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5862ec34544SRui Ueyama   }
5872ec34544SRui Ueyama   return Cmd;
5882ec34544SRui Ueyama }
5892ec34544SRui Ueyama 
5902ec34544SRui Ueyama InputSectionDescription *
5912ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5922ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5932ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5942ec34544SRui Ueyama   if (Tok == "KEEP") {
5952ec34544SRui Ueyama     expect("(");
5962ec34544SRui Ueyama     StringRef FilePattern = next();
5972ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5982ec34544SRui Ueyama     expect(")");
599ac27de9dSRui Ueyama     Script->KeptSections.push_back(Cmd);
6002ec34544SRui Ueyama     return Cmd;
6012ec34544SRui Ueyama   }
6022ec34544SRui Ueyama   return readInputSectionRules(Tok);
6032ec34544SRui Ueyama }
6042ec34544SRui Ueyama 
6052ec34544SRui Ueyama void ScriptParser::readSort() {
6062ec34544SRui Ueyama   expect("(");
6072ec34544SRui Ueyama   expect("CONSTRUCTORS");
6082ec34544SRui Ueyama   expect(")");
6092ec34544SRui Ueyama }
6102ec34544SRui Ueyama 
61123af89ccSRui Ueyama AssertCommand *ScriptParser::readAssert() {
61223af89ccSRui Ueyama   return make<AssertCommand>(readAssertExpr());
61323af89ccSRui Ueyama }
61423af89ccSRui Ueyama 
61523af89ccSRui Ueyama Expr ScriptParser::readAssertExpr() {
6162ec34544SRui Ueyama   expect("(");
6172ec34544SRui Ueyama   Expr E = readExpr();
6182ec34544SRui Ueyama   expect(",");
6192ec34544SRui Ueyama   StringRef Msg = unquote(next());
6202ec34544SRui Ueyama   expect(")");
621b579c439SRui Ueyama 
6222ec34544SRui Ueyama   return [=] {
6232ec34544SRui Ueyama     if (!E().getValue())
6242ec34544SRui Ueyama       error(Msg);
6252ec34544SRui Ueyama     return Script->getDot();
6262ec34544SRui Ueyama   };
6272ec34544SRui Ueyama }
6282ec34544SRui Ueyama 
6292ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
6302ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
6312ec34544SRui Ueyama // what GNU linkers do.
6322ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
6332ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
6342ec34544SRui Ueyama   expect("(");
6358acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
6362ec34544SRui Ueyama   expect(")");
6372ec34544SRui Ueyama   return V;
6382ec34544SRui Ueyama }
6392ec34544SRui Ueyama 
6401c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
6411c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
6421c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
6433271d370SRui Ueyama //
6443271d370SRui Ueyama // An output section name can be followed by an address expression
6451c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
64697f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
6471c08e9f5SGeorge Rimar // of directive.
6483271d370SRui Ueyama //
649b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
650fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
6518c022ca7SRafael Espindola void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
6523271d370SRui Ueyama   if (consume("(")) {
6533271d370SRui Ueyama     if (consume("NOLOAD")) {
6543271d370SRui Ueyama       expect(")");
6553271d370SRui Ueyama       Cmd->Noload = true;
6563271d370SRui Ueyama       return;
6573271d370SRui Ueyama     }
6581c08e9f5SGeorge Rimar     if (consume("COPY") || consume("INFO") || consume("OVERLAY")) {
6591c08e9f5SGeorge Rimar       expect(")");
6601c08e9f5SGeorge Rimar       Cmd->NonAlloc = true;
6611c08e9f5SGeorge Rimar       return;
6621c08e9f5SGeorge Rimar     }
6633271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6643271d370SRui Ueyama     expect(")");
6653271d370SRui Ueyama   } else {
6663271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6673271d370SRui Ueyama   }
6683271d370SRui Ueyama 
669fbb0463fSGeorge Rimar   if (consume("(")) {
670fbb0463fSGeorge Rimar     expect("NOLOAD");
671fbb0463fSGeorge Rimar     expect(")");
672fbb0463fSGeorge Rimar     Cmd->Noload = true;
673fbb0463fSGeorge Rimar   }
674fbb0463fSGeorge Rimar }
675fbb0463fSGeorge Rimar 
676f22ec9ddSGeorge Rimar static Expr checkAlignment(Expr E, std::string &Loc) {
677f22ec9ddSGeorge Rimar   return [=] {
678f22ec9ddSGeorge Rimar     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
679f22ec9ddSGeorge Rimar     if (!isPowerOf2_64(Alignment)) {
680f22ec9ddSGeorge Rimar       error(Loc + ": alignment must be power of 2");
681f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
682f22ec9ddSGeorge Rimar     }
683f22ec9ddSGeorge Rimar     return Alignment;
684f22ec9ddSGeorge Rimar   };
685f22ec9ddSGeorge Rimar }
686f22ec9ddSGeorge Rimar 
6878c022ca7SRafael Espindola OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
6888c022ca7SRafael Espindola   OutputSection *Cmd =
6898c022ca7SRafael Espindola       Script->createOutputSection(OutSec, getCurrentLocation());
6903271d370SRui Ueyama 
691c4df670dSGeorge Rimar   size_t SymbolsReferenced = Script->ReferencedSymbols.size();
692c4df670dSGeorge Rimar 
6933271d370SRui Ueyama   if (peek() != ":")
6943271d370SRui Ueyama     readSectionAddressType(Cmd);
6952ec34544SRui Ueyama   expect(":");
6962ec34544SRui Ueyama 
697f22ec9ddSGeorge Rimar   std::string Location = getCurrentLocation();
6982ec34544SRui Ueyama   if (consume("AT"))
6992ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
7002ec34544SRui Ueyama   if (consume("ALIGN"))
701f22ec9ddSGeorge Rimar     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
7022ec34544SRui Ueyama   if (consume("SUBALIGN"))
703f22ec9ddSGeorge Rimar     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
7042ec34544SRui Ueyama 
7052ec34544SRui Ueyama   // Parse constraints.
7062ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
7072ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
7082ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
7092ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
7102ec34544SRui Ueyama   expect("{");
7112ec34544SRui Ueyama 
712b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
7132ec34544SRui Ueyama     StringRef Tok = next();
7142ec34544SRui Ueyama     if (Tok == ";") {
7152ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
716b579c439SRui Ueyama     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
7176b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Assign);
718f0403c60SRui Ueyama     } else if (ByteCommand *Data = readByteCommand(Tok)) {
7196b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Data);
7202ec34544SRui Ueyama     } else if (Tok == "ASSERT") {
7216b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readAssert());
7222ec34544SRui Ueyama       expect(";");
7232ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
7242ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
7252ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
7262ec34544SRui Ueyama       // For ELF, we should ignore.
7272ec34544SRui Ueyama     } else if (Tok == "FILL") {
7282ec34544SRui Ueyama       Cmd->Filler = readFill();
7292ec34544SRui Ueyama     } else if (Tok == "SORT") {
7302ec34544SRui Ueyama       readSort();
7312ec34544SRui Ueyama     } else if (peek() == "(") {
7326b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
7332ec34544SRui Ueyama     } else {
7342ec34544SRui Ueyama       setError("unknown command " + Tok);
7352ec34544SRui Ueyama     }
7362ec34544SRui Ueyama   }
7372ec34544SRui Ueyama 
7382ec34544SRui Ueyama   if (consume(">"))
7392ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
7402ec34544SRui Ueyama 
7415d01a8beSGeorge Rimar   if (consume("AT")) {
7425d01a8beSGeorge Rimar     expect(">");
7435d01a8beSGeorge Rimar     Cmd->LMARegionName = next();
7445d01a8beSGeorge Rimar   }
7455d01a8beSGeorge Rimar 
7465d01a8beSGeorge Rimar   if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
7475d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
7485d01a8beSGeorge Rimar 
7492ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
7502ec34544SRui Ueyama 
7512ec34544SRui Ueyama   if (consume("="))
7528acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
7532ec34544SRui Ueyama   else if (peek().startswith("="))
7548acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
7552ec34544SRui Ueyama 
7562ec34544SRui Ueyama   // Consume optional comma following output section command.
7572ec34544SRui Ueyama   consume(",");
7582ec34544SRui Ueyama 
759c4df670dSGeorge Rimar   if (Script->ReferencedSymbols.size() > SymbolsReferenced)
760c4df670dSGeorge Rimar     Cmd->ExpressionsUseSymbols = true;
7612ec34544SRui Ueyama   return Cmd;
7622ec34544SRui Ueyama }
7632ec34544SRui Ueyama 
7648acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
7658acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
7662ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
7672ec34544SRui Ueyama //
7688acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
7698acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
7708acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
7718acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
772b58079d4SRui Ueyama   uint32_t V = 0;
773ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
7742ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
775b58079d4SRui Ueyama 
776b58079d4SRui Ueyama   uint32_t Buf;
777b58079d4SRui Ueyama   write32be(&Buf, V);
778b58079d4SRui Ueyama   return Buf;
7792ec34544SRui Ueyama }
7802ec34544SRui Ueyama 
7812ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
7822ec34544SRui Ueyama   expect("(");
7832ec34544SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
7842ec34544SRui Ueyama   Cmd->Provide = Provide;
7852ec34544SRui Ueyama   Cmd->Hidden = Hidden;
7862ec34544SRui Ueyama   expect(")");
7872ec34544SRui Ueyama   return Cmd;
7882ec34544SRui Ueyama }
7892ec34544SRui Ueyama 
7902ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
791e88b76a9SGeorge Rimar   size_t OldPos = Pos;
7922ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
793e88b76a9SGeorge Rimar   if (peek() == "=" || peek() == "+=")
7942ec34544SRui Ueyama     Cmd = readAssignment(Tok);
795e88b76a9SGeorge Rimar   else if (Tok == "PROVIDE")
7962ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
797e88b76a9SGeorge Rimar   else if (Tok == "HIDDEN")
7982ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
799e88b76a9SGeorge Rimar   else if (Tok == "PROVIDE_HIDDEN")
8002ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
801e88b76a9SGeorge Rimar 
802e88b76a9SGeorge Rimar   if (Cmd) {
803e88b76a9SGeorge Rimar     Cmd->CommandString =
804e88b76a9SGeorge Rimar         Tok.str() + " " +
805e88b76a9SGeorge Rimar         llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
806e88b76a9SGeorge Rimar     expect(";");
8072ec34544SRui Ueyama   }
8082ec34544SRui Ueyama   return Cmd;
8092ec34544SRui Ueyama }
8102ec34544SRui Ueyama 
8112ec34544SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
8122ec34544SRui Ueyama   StringRef Op = next();
8132ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
8142ec34544SRui Ueyama   Expr E = readExpr();
8152ec34544SRui Ueyama   if (Op == "+=") {
8162ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
817722221f5SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
8182ec34544SRui Ueyama   }
819e88b76a9SGeorge Rimar   return make<SymbolAssignment>(Name, E, getCurrentLocation());
8202ec34544SRui Ueyama }
8212ec34544SRui Ueyama 
8222ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
8232ec34544SRui Ueyama // script expression.
8242ec34544SRui Ueyama Expr ScriptParser::readExpr() {
8252ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
8262ec34544SRui Ueyama   // they apply different tokenization rules.
8272ec34544SRui Ueyama   bool Orig = InExpr;
8282ec34544SRui Ueyama   InExpr = true;
8292ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
8302ec34544SRui Ueyama   InExpr = Orig;
8312ec34544SRui Ueyama   return E;
8322ec34544SRui Ueyama }
8332ec34544SRui Ueyama 
8347b91e213SGeorge Rimar Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
8352ec34544SRui Ueyama   if (Op == "+")
8362ec34544SRui Ueyama     return [=] { return add(L(), R()); };
8372ec34544SRui Ueyama   if (Op == "-")
8382ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
839b579c439SRui Ueyama   if (Op == "*")
8401d20222aSRui Ueyama     return [=] { return L().getValue() * R().getValue(); };
8417b91e213SGeorge Rimar   if (Op == "/") {
8427b91e213SGeorge Rimar     std::string Loc = getCurrentLocation();
8437b91e213SGeorge Rimar     return [=]() -> uint64_t {
8447b91e213SGeorge Rimar       if (uint64_t RV = R().getValue())
8457b91e213SGeorge Rimar         return L().getValue() / RV;
8467b91e213SGeorge Rimar       error(Loc + ": division by zero");
847067617f9SRui Ueyama       return 0;
8487b91e213SGeorge Rimar     };
8497b91e213SGeorge Rimar   }
8507b91e213SGeorge Rimar   if (Op == "%") {
8517b91e213SGeorge Rimar     std::string Loc = getCurrentLocation();
8527b91e213SGeorge Rimar     return [=]() -> uint64_t {
8537b91e213SGeorge Rimar       if (uint64_t RV = R().getValue())
8547b91e213SGeorge Rimar         return L().getValue() % RV;
8557b91e213SGeorge Rimar       error(Loc + ": modulo by zero");
856067617f9SRui Ueyama       return 0;
8577b91e213SGeorge Rimar     };
8587b91e213SGeorge Rimar   }
8592ec34544SRui Ueyama   if (Op == "<<")
8607e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
8612ec34544SRui Ueyama   if (Op == ">>")
8627e915511SRui Ueyama     return [=] { return L().getValue() >> R().getValue(); };
8632ec34544SRui Ueyama   if (Op == "<")
8642ec34544SRui Ueyama     return [=] { return L().getValue() < R().getValue(); };
8652ec34544SRui Ueyama   if (Op == ">")
8662ec34544SRui Ueyama     return [=] { return L().getValue() > R().getValue(); };
8672ec34544SRui Ueyama   if (Op == ">=")
8682ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
8692ec34544SRui Ueyama   if (Op == "<=")
8702ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
8712ec34544SRui Ueyama   if (Op == "==")
8722ec34544SRui Ueyama     return [=] { return L().getValue() == R().getValue(); };
8732ec34544SRui Ueyama   if (Op == "!=")
8742ec34544SRui Ueyama     return [=] { return L().getValue() != R().getValue(); };
8752ec34544SRui Ueyama   if (Op == "&")
8762ec34544SRui Ueyama     return [=] { return bitAnd(L(), R()); };
8772ec34544SRui Ueyama   if (Op == "|")
8782ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
8792ec34544SRui Ueyama   llvm_unreachable("invalid operator");
8802ec34544SRui Ueyama }
8812ec34544SRui Ueyama 
8822ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
8832ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
8842ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
885b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
8862ec34544SRui Ueyama     // Read an operator and an expression.
8872ec34544SRui Ueyama     if (consume("?"))
8882ec34544SRui Ueyama       return readTernary(Lhs);
8892ec34544SRui Ueyama     StringRef Op1 = peek();
8902ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
8912ec34544SRui Ueyama       break;
8922ec34544SRui Ueyama     skip();
8932ec34544SRui Ueyama     Expr Rhs = readPrimary();
8942ec34544SRui Ueyama 
8952ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
8962ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
8972ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
8982ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
8992ec34544SRui Ueyama     while (!atEOF()) {
9002ec34544SRui Ueyama       StringRef Op2 = peek();
9012ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
9022ec34544SRui Ueyama         break;
9032ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
9042ec34544SRui Ueyama     }
9052ec34544SRui Ueyama 
9062ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
9072ec34544SRui Ueyama   }
9082ec34544SRui Ueyama   return Lhs;
9092ec34544SRui Ueyama }
9102ec34544SRui Ueyama 
9115fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
9125fb17128SGeorge Rimar   std::string Location = getCurrentLocation();
9135fb17128SGeorge Rimar   return [=]() -> uint64_t {
9145fb17128SGeorge Rimar     if (Target)
9152ec34544SRui Ueyama       return Target->PageSize;
9165fb17128SGeorge Rimar     error(Location + ": unable to calculate page size");
9175fb17128SGeorge Rimar     return 4096; // Return a dummy value.
9185fb17128SGeorge Rimar   };
9195fb17128SGeorge Rimar }
9205fb17128SGeorge Rimar 
9215fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
9225fb17128SGeorge Rimar   StringRef S = readParenLiteral();
9235fb17128SGeorge Rimar   if (S == "COMMONPAGESIZE")
9245fb17128SGeorge Rimar     return getPageSize();
9252ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
9265fb17128SGeorge Rimar     return [] { return Config->MaxPageSize; };
9275fb17128SGeorge Rimar   setError("unknown constant: " + S);
928b068b037SGeorge Rimar   return [] { return 0; };
9292ec34544SRui Ueyama }
9302ec34544SRui Ueyama 
9315c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
9325c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
9335c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
9345c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
9352ec34544SRui Ueyama   // Hexadecimal
9365c65088fSRui Ueyama   uint64_t Val;
9374092016bSRui Ueyama   if (Tok.startswith_lower("0x")) {
9384092016bSRui Ueyama     if (!to_integer(Tok.substr(2), Val, 16))
9394092016bSRui Ueyama       return None;
9405c65088fSRui Ueyama     return Val;
9414092016bSRui Ueyama   }
9424092016bSRui Ueyama   if (Tok.endswith_lower("H")) {
9434092016bSRui Ueyama     if (!to_integer(Tok.drop_back(), Val, 16))
9444092016bSRui Ueyama       return None;
9455c65088fSRui Ueyama     return Val;
9464092016bSRui Ueyama   }
9472ec34544SRui Ueyama 
9482ec34544SRui Ueyama   // Decimal
9492ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
950ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9515c65088fSRui Ueyama       return None;
9525c65088fSRui Ueyama     return Val * 1024;
9532ec34544SRui Ueyama   }
9545c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
955ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9565c65088fSRui Ueyama       return None;
9575c65088fSRui Ueyama     return Val * 1024 * 1024;
9585c65088fSRui Ueyama   }
959ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
9605c65088fSRui Ueyama     return None;
9615c65088fSRui Ueyama   return Val;
9622ec34544SRui Ueyama }
9632ec34544SRui Ueyama 
964f0403c60SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
965b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
9662ec34544SRui Ueyama                  .Case("BYTE", 1)
9672ec34544SRui Ueyama                  .Case("SHORT", 2)
9682ec34544SRui Ueyama                  .Case("LONG", 4)
9692ec34544SRui Ueyama                  .Case("QUAD", 8)
9702ec34544SRui Ueyama                  .Default(-1);
9712ec34544SRui Ueyama   if (Size == -1)
9722ec34544SRui Ueyama     return nullptr;
97384bcabcbSGeorge Rimar 
97484bcabcbSGeorge Rimar   size_t OldPos = Pos;
97584bcabcbSGeorge Rimar   Expr E = readParenExpr();
97684bcabcbSGeorge Rimar   std::string CommandString =
97784bcabcbSGeorge Rimar       Tok.str() + " " +
97884bcabcbSGeorge Rimar       llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
97984bcabcbSGeorge Rimar   return make<ByteCommand>(E, Size, CommandString);
9802ec34544SRui Ueyama }
9812ec34544SRui Ueyama 
9822ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
9832ec34544SRui Ueyama   expect("(");
9845e9c7762SRafael Espindola   bool Orig = InExpr;
9855e9c7762SRafael Espindola   InExpr = false;
9862ec34544SRui Ueyama   StringRef Tok = next();
9875e9c7762SRafael Espindola   InExpr = Orig;
9882ec34544SRui Ueyama   expect(")");
9892ec34544SRui Ueyama   return Tok;
9902ec34544SRui Ueyama }
9912ec34544SRui Ueyama 
992617e2f98SRui Ueyama static void checkIfExists(OutputSection *Cmd, StringRef Location) {
99305c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
99405c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
99505c4f67cSRafael Espindola }
99605c4f67cSRafael Espindola 
9972ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
9982ec34544SRui Ueyama   if (peek() == "(")
9992ec34544SRui Ueyama     return readParenExpr();
10002ec34544SRui Ueyama 
10015c65088fSRui Ueyama   if (consume("~")) {
10022ec34544SRui Ueyama     Expr E = readPrimary();
1003b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
10042ec34544SRui Ueyama   }
10056f1d954eSHafiz Abid Qadeer   if (consume("!")) {
10066f1d954eSHafiz Abid Qadeer     Expr E = readPrimary();
10076f1d954eSHafiz Abid Qadeer     return [=] { return !E().getValue(); };
10086f1d954eSHafiz Abid Qadeer   }
10095c65088fSRui Ueyama   if (consume("-")) {
10102ec34544SRui Ueyama     Expr E = readPrimary();
1011b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
10122ec34544SRui Ueyama   }
10132ec34544SRui Ueyama 
10145c65088fSRui Ueyama   StringRef Tok = next();
10155c65088fSRui Ueyama   std::string Location = getCurrentLocation();
10165c65088fSRui Ueyama 
10172ec34544SRui Ueyama   // Built-in functions are parsed here.
10182ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
10192ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
10202ec34544SRui Ueyama     Expr Inner = readParenExpr();
10212ec34544SRui Ueyama     return [=] {
10222ec34544SRui Ueyama       ExprValue I = Inner();
10232ec34544SRui Ueyama       I.ForceAbsolute = true;
10242ec34544SRui Ueyama       return I;
10252ec34544SRui Ueyama     };
10262ec34544SRui Ueyama   }
10272ec34544SRui Ueyama   if (Tok == "ADDR") {
10282ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10294fbe3518SRui Ueyama     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
103041c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
10314fbe3518SRui Ueyama       checkIfExists(Sec, Location);
10324fbe3518SRui Ueyama       return {Sec, false, 0, Location};
103341c7ab4aSGeorge Rimar     };
10342ec34544SRui Ueyama   }
10352ec34544SRui Ueyama   if (Tok == "ALIGN") {
10362ec34544SRui Ueyama     expect("(");
10372ec34544SRui Ueyama     Expr E = readExpr();
1038f22ec9ddSGeorge Rimar     if (consume(")")) {
1039f22ec9ddSGeorge Rimar       E = checkAlignment(E, Location);
1040f22ec9ddSGeorge Rimar       return [=] { return alignTo(Script->getDot(), E().getValue()); };
1041f22ec9ddSGeorge Rimar     }
1042b579c439SRui Ueyama     expect(",");
1043f22ec9ddSGeorge Rimar     Expr E2 = checkAlignment(readExpr(), Location);
10442ec34544SRui Ueyama     expect(")");
10453c6de1a6SPetr Hosek     return [=] {
10463c6de1a6SPetr Hosek       ExprValue V = E();
1047f22ec9ddSGeorge Rimar       V.Alignment = E2().getValue();
10483c6de1a6SPetr Hosek       return V;
10493c6de1a6SPetr Hosek     };
10502ec34544SRui Ueyama   }
10512ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
10522ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10538c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1054617e2f98SRui Ueyama     return [=] {
1055617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1056617e2f98SRui Ueyama       return Cmd->Alignment;
1057617e2f98SRui Ueyama     };
10582ec34544SRui Ueyama   }
10592ec34544SRui Ueyama   if (Tok == "ASSERT")
106023af89ccSRui Ueyama     return readAssertExpr();
10615fb17128SGeorge Rimar   if (Tok == "CONSTANT")
10625fb17128SGeorge Rimar     return readConstant();
10632ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
10642ec34544SRui Ueyama     expect("(");
10652ec34544SRui Ueyama     Expr E = readExpr();
10662ec34544SRui Ueyama     expect(",");
10672ec34544SRui Ueyama     readExpr();
10682ec34544SRui Ueyama     expect(")");
106960833f6eSGeorge Rimar     return [=] {
107060833f6eSGeorge Rimar       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
107160833f6eSGeorge Rimar     };
10722ec34544SRui Ueyama   }
10732ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
10742ec34544SRui Ueyama     expect("(");
10752ec34544SRui Ueyama     expect(".");
10762ec34544SRui Ueyama     expect(")");
10772ec34544SRui Ueyama     return [] { return Script->getDot(); };
10782ec34544SRui Ueyama   }
10792ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
10802ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
10812ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
10822ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
10832ec34544SRui Ueyama     expect("(");
10842ec34544SRui Ueyama     readExpr();
10852ec34544SRui Ueyama     expect(",");
10862ec34544SRui Ueyama     readExpr();
10872ec34544SRui Ueyama     expect(")");
10885fb17128SGeorge Rimar     Expr E = getPageSize();
10895fb17128SGeorge Rimar     return [=] { return alignTo(Script->getDot(), E().getValue()); };
10902ec34544SRui Ueyama   }
10912ec34544SRui Ueyama   if (Tok == "DEFINED") {
10922ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10939b18f50fSRui Ueyama     return [=] { return Symtab->find(Name) ? 1 : 0; };
10942ec34544SRui Ueyama   }
109591b95b61SRui Ueyama   if (Tok == "LENGTH") {
109691b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1097b068b037SGeorge Rimar     if (Script->MemoryRegions.count(Name) == 0) {
109891b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1099b068b037SGeorge Rimar       return [] { return 0; };
1100b068b037SGeorge Rimar     }
1101ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Length; };
110291b95b61SRui Ueyama   }
11032ec34544SRui Ueyama   if (Tok == "LOADADDR") {
11042ec34544SRui Ueyama     StringRef Name = readParenLiteral();
11058c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1106617e2f98SRui Ueyama     return [=] {
1107617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1108617e2f98SRui Ueyama       return Cmd->getLMA();
1109617e2f98SRui Ueyama     };
11102ec34544SRui Ueyama   }
1111fd11560fSGeorge Rimar   if (Tok == "MAX" || Tok == "MIN") {
1112fd11560fSGeorge Rimar     expect("(");
1113fd11560fSGeorge Rimar     Expr A = readExpr();
1114fd11560fSGeorge Rimar     expect(",");
1115fd11560fSGeorge Rimar     Expr B = readExpr();
1116fd11560fSGeorge Rimar     expect(")");
1117fd11560fSGeorge Rimar     if (Tok == "MIN")
1118fd11560fSGeorge Rimar       return [=] { return std::min(A().getValue(), B().getValue()); };
1119fd11560fSGeorge Rimar     return [=] { return std::max(A().getValue(), B().getValue()); };
1120fd11560fSGeorge Rimar   }
112191b95b61SRui Ueyama   if (Tok == "ORIGIN") {
112291b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1123b068b037SGeorge Rimar     if (Script->MemoryRegions.count(Name) == 0) {
112491b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1125b068b037SGeorge Rimar       return [] { return 0; };
1126b068b037SGeorge Rimar     }
1127ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Origin; };
112891b95b61SRui Ueyama   }
11292ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
11302ec34544SRui Ueyama     expect("(");
11312ec34544SRui Ueyama     skip();
11322ec34544SRui Ueyama     expect(",");
11332ec34544SRui Ueyama     Expr E = readExpr();
11342ec34544SRui Ueyama     expect(")");
11352ec34544SRui Ueyama     return [=] { return E(); };
11362ec34544SRui Ueyama   }
11372ec34544SRui Ueyama   if (Tok == "SIZEOF") {
11382ec34544SRui Ueyama     StringRef Name = readParenLiteral();
11398c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
114005c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
114105c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
114205c4f67cSRafael Espindola     // be empty.
11438c022ca7SRafael Espindola     return [=] { return Cmd->Size; };
11442ec34544SRui Ueyama   }
11452ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
11462ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
11472ec34544SRui Ueyama 
11484eb2eccbSRui Ueyama   // Tok is the dot.
11494eb2eccbSRui Ueyama   if (Tok == ".")
1150722221f5SRui Ueyama     return [=] { return Script->getSymbolValue(Tok, Location); };
11514eb2eccbSRui Ueyama 
11522ec34544SRui Ueyama   // Tok is a literal number.
11535c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11545c65088fSRui Ueyama     return [=] { return *Val; };
11552ec34544SRui Ueyama 
11562ec34544SRui Ueyama   // Tok is a symbol name.
11572ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
11582ec34544SRui Ueyama     setError("malformed number: " + Tok);
1159ac27de9dSRui Ueyama   Script->ReferencedSymbols.push_back(Tok);
1160722221f5SRui Ueyama   return [=] { return Script->getSymbolValue(Tok, Location); };
11612ec34544SRui Ueyama }
11622ec34544SRui Ueyama 
11632ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
11642ec34544SRui Ueyama   Expr L = readExpr();
11652ec34544SRui Ueyama   expect(":");
11662ec34544SRui Ueyama   Expr R = readExpr();
11672ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
11682ec34544SRui Ueyama }
11692ec34544SRui Ueyama 
11702ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
11712ec34544SRui Ueyama   expect("(");
11722ec34544SRui Ueyama   Expr E = readExpr();
11732ec34544SRui Ueyama   expect(")");
11742ec34544SRui Ueyama   return E;
11752ec34544SRui Ueyama }
11762ec34544SRui Ueyama 
11772ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
11782ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
1179b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
11802ec34544SRui Ueyama     StringRef Tok = next();
11812ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
11822ec34544SRui Ueyama   }
11832ec34544SRui Ueyama   return Phdrs;
11842ec34544SRui Ueyama }
11852ec34544SRui Ueyama 
11862ec34544SRui Ueyama // Read a program header type name. The next token must be a
11872ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
11882ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
11892ec34544SRui Ueyama   StringRef Tok = next();
11905c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11915c65088fSRui Ueyama     return *Val;
11922ec34544SRui Ueyama 
11932ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
11942ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
11952ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
11962ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
11972ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
11982ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
11992ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
12002ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
12012ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
12022ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
12032ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
12042ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
12052ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
12062ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
12072ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
12082ec34544SRui Ueyama                      .Default(-1);
12092ec34544SRui Ueyama 
12102ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
12112ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
12122ec34544SRui Ueyama     return PT_NULL;
12132ec34544SRui Ueyama   }
12142ec34544SRui Ueyama   return Ret;
12152ec34544SRui Ueyama }
12162ec34544SRui Ueyama 
12172ec34544SRui Ueyama // Reads an anonymous version declaration.
12182ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
12192ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12202ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12212ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
12222ec34544SRui Ueyama 
12232ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
12242ec34544SRui Ueyama     if (V.Name == "*")
12252ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
12262ec34544SRui Ueyama     else
12272ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
12282ec34544SRui Ueyama   }
12292ec34544SRui Ueyama 
12302ec34544SRui Ueyama   for (SymbolVersion V : Globals)
12312ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
12322ec34544SRui Ueyama 
12332ec34544SRui Ueyama   expect(";");
12342ec34544SRui Ueyama }
12352ec34544SRui Ueyama 
12362ec34544SRui Ueyama // Reads a non-anonymous version definition,
12372ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
12382ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
12392ec34544SRui Ueyama   // Read a symbol list.
12402ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12412ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12422ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
12432ec34544SRui Ueyama 
12442ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
12452ec34544SRui Ueyama     if (V.Name == "*")
12462ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
12472ec34544SRui Ueyama     else
12482ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
12492ec34544SRui Ueyama   }
12502ec34544SRui Ueyama 
12512ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
12522ec34544SRui Ueyama   VersionDefinition Ver;
12532ec34544SRui Ueyama   Ver.Name = VerStr;
12542ec34544SRui Ueyama   Ver.Globals = Globals;
12552ec34544SRui Ueyama 
12562ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
12572ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
12582ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
12592ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
12602ec34544SRui Ueyama 
12612ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
12622ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
12632ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
12642ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
12652ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
12662ec34544SRui Ueyama   if (peek() != ";")
12672ec34544SRui Ueyama     skip();
12682ec34544SRui Ueyama   expect(";");
12692ec34544SRui Ueyama }
12702ec34544SRui Ueyama 
12711e77ad14SRui Ueyama static bool hasWildcard(StringRef S) {
12721e77ad14SRui Ueyama   return S.find_first_of("?*[") != StringRef::npos;
12731e77ad14SRui Ueyama }
12741e77ad14SRui Ueyama 
12752ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
12762ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
12772ec34544SRui Ueyama ScriptParser::readSymbols() {
12782ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12792ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12802ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
12812ec34544SRui Ueyama 
1282b8a59c8aSBob Haarman   while (!errorCount()) {
12832ec34544SRui Ueyama     if (consume("}"))
12842ec34544SRui Ueyama       break;
12852ec34544SRui Ueyama     if (consumeLabel("local")) {
12862ec34544SRui Ueyama       V = &Locals;
12872ec34544SRui Ueyama       continue;
12882ec34544SRui Ueyama     }
12892ec34544SRui Ueyama     if (consumeLabel("global")) {
12902ec34544SRui Ueyama       V = &Globals;
12912ec34544SRui Ueyama       continue;
12922ec34544SRui Ueyama     }
12932ec34544SRui Ueyama 
12942ec34544SRui Ueyama     if (consume("extern")) {
12952ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
12962ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
12972ec34544SRui Ueyama     } else {
12982ec34544SRui Ueyama       StringRef Tok = next();
12992ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
13002ec34544SRui Ueyama     }
13012ec34544SRui Ueyama     expect(";");
13022ec34544SRui Ueyama   }
13032ec34544SRui Ueyama   return {Locals, Globals};
13042ec34544SRui Ueyama }
13052ec34544SRui Ueyama 
13062ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
13072ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
130817324d8bSRui Ueyama //
130917324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
131017324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
13112ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
13122ec34544SRui Ueyama   StringRef Tok = next();
13132ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
13142ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
13152ec34544SRui Ueyama     setError("Unknown language");
13162ec34544SRui Ueyama   expect("{");
13172ec34544SRui Ueyama 
13182ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
1319b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
13202ec34544SRui Ueyama     StringRef Tok = next();
13212ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
13222ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
132317324d8bSRui Ueyama     if (consume("}"))
132417324d8bSRui Ueyama       return Ret;
13252ec34544SRui Ueyama     expect(";");
13262ec34544SRui Ueyama   }
13272ec34544SRui Ueyama 
13282ec34544SRui Ueyama   expect("}");
13292ec34544SRui Ueyama   return Ret;
13302ec34544SRui Ueyama }
13312ec34544SRui Ueyama 
13322ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
13332ec34544SRui Ueyama                                             StringRef S3) {
1334b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
13352ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
13362ec34544SRui Ueyama     return 0;
13372ec34544SRui Ueyama   }
13382ec34544SRui Ueyama   expect("=");
1339040af7deSRui Ueyama   return readExpr()().getValue();
13402ec34544SRui Ueyama }
13412ec34544SRui Ueyama 
13422ec34544SRui Ueyama // Parse the MEMORY command as specified in:
13432ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
13442ec34544SRui Ueyama //
13452ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
13462ec34544SRui Ueyama void ScriptParser::readMemory() {
13472ec34544SRui Ueyama   expect("{");
1348b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
13492ec34544SRui Ueyama     StringRef Name = next();
13502ec34544SRui Ueyama 
13512ec34544SRui Ueyama     uint32_t Flags = 0;
13522ec34544SRui Ueyama     uint32_t NegFlags = 0;
13532ec34544SRui Ueyama     if (consume("(")) {
13542ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
13552ec34544SRui Ueyama       expect(")");
13562ec34544SRui Ueyama     }
13572ec34544SRui Ueyama     expect(":");
13582ec34544SRui Ueyama 
13592ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
13602ec34544SRui Ueyama     expect(",");
13612ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
13622ec34544SRui Ueyama 
13635f37541cSGeorge Rimar     // Add the memory region to the region map.
1364490f0a4dSRafael Espindola     MemoryRegion *MR =
1365490f0a4dSRafael Espindola         make<MemoryRegion>(Name, Origin, Length, Flags, NegFlags);
13660984cfa9SGeorge Rimar     if (!Script->MemoryRegions.insert({Name, MR}).second)
13670984cfa9SGeorge Rimar       setError("region '" + Name + "' already defined");
13682ec34544SRui Ueyama   }
13692ec34544SRui Ueyama }
13702ec34544SRui Ueyama 
13712ec34544SRui Ueyama // This function parses the attributes used to match against section
13722ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
13732ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
13742ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
13752ec34544SRui Ueyama   uint32_t Flags = 0;
13762ec34544SRui Ueyama   uint32_t NegFlags = 0;
13772ec34544SRui Ueyama   bool Invert = false;
13782ec34544SRui Ueyama 
13792ec34544SRui Ueyama   for (char C : next().lower()) {
13802ec34544SRui Ueyama     uint32_t Flag = 0;
13812ec34544SRui Ueyama     if (C == '!')
13822ec34544SRui Ueyama       Invert = !Invert;
13832ec34544SRui Ueyama     else if (C == 'w')
13842ec34544SRui Ueyama       Flag = SHF_WRITE;
13852ec34544SRui Ueyama     else if (C == 'x')
13862ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
13872ec34544SRui Ueyama     else if (C == 'a')
13882ec34544SRui Ueyama       Flag = SHF_ALLOC;
13892ec34544SRui Ueyama     else if (C != 'r')
13902ec34544SRui Ueyama       setError("invalid memory region attribute");
13912ec34544SRui Ueyama 
13922ec34544SRui Ueyama     if (Invert)
13932ec34544SRui Ueyama       NegFlags |= Flag;
13942ec34544SRui Ueyama     else
13952ec34544SRui Ueyama       Flags |= Flag;
13962ec34544SRui Ueyama   }
13972ec34544SRui Ueyama   return {Flags, NegFlags};
13982ec34544SRui Ueyama }
13992ec34544SRui Ueyama 
14002ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
14012ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
14022ec34544SRui Ueyama }
14032ec34544SRui Ueyama 
14042ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
14052ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
14062ec34544SRui Ueyama }
14072ec34544SRui Ueyama 
14082ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
14092ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
14102ec34544SRui Ueyama }
14118c7e8cceSPetr Hosek 
14128c7e8cceSPetr Hosek void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
14138c7e8cceSPetr Hosek   ScriptParser(MB).readDefsym(Name);
14148c7e8cceSPetr Hosek }
1415