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 
78*d30a78b3SGeorge Rimar   SymbolAssignment *readSymbolAssignment(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);
92*d30a78b3SGeorge Rimar   SymbolAssignment *readAssignment(StringRef Tok);
932ec34544SRui Ueyama   void readSort();
94*d30a78b3SGeorge Rimar   Expr readAssert();
955fb17128SGeorge Rimar   Expr readConstant();
965fb17128SGeorge Rimar   Expr getPageSize();
972ec34544SRui Ueyama 
982ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
992ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1002ec34544SRui Ueyama 
1017b91e213SGeorge Rimar   Expr combine(StringRef Op, Expr L, Expr R);
1022ec34544SRui Ueyama   Expr readExpr();
1032ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1042ec34544SRui Ueyama   StringRef readParenLiteral();
1052ec34544SRui Ueyama   Expr readPrimary();
1062ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1072ec34544SRui Ueyama   Expr readParenExpr();
1082ec34544SRui Ueyama 
1092ec34544SRui Ueyama   // For parsing version script.
1102ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1112ec34544SRui Ueyama   void readAnonymousDeclaration();
1122ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1132ec34544SRui Ueyama 
1142ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1152ec34544SRui Ueyama   readSymbols();
1162ec34544SRui Ueyama 
117fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1182ec34544SRui Ueyama   bool IsUnderSysroot;
1190440be4aSRui Ueyama 
1200440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1210440be4aSRui Ueyama   StringSet<> Seen;
1222ec34544SRui Ueyama };
12396b3fe02SRui Ueyama } // namespace
1242ec34544SRui Ueyama 
1251e77ad14SRui Ueyama static StringRef unquote(StringRef S) {
1261e77ad14SRui Ueyama   if (S.startswith("\""))
1271e77ad14SRui Ueyama     return S.substr(1, S.size() - 2);
1281e77ad14SRui Ueyama   return S;
1291e77ad14SRui Ueyama }
1301e77ad14SRui Ueyama 
1312ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1322ec34544SRui Ueyama   if (Config->Sysroot == "")
1332ec34544SRui Ueyama     return false;
1342ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1352ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1362ec34544SRui Ueyama       return true;
1372ec34544SRui Ueyama   return false;
1382ec34544SRui Ueyama }
1392ec34544SRui Ueyama 
1402ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1412ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1422ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
14323be5e8dSRafael Espindola   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
1442ec34544SRui Ueyama     std::swap(A, B);
1452ec34544SRui Ueyama   if (!B.isAbsolute())
14641c7ab4aSGeorge Rimar     error(A.Loc + ": at least one side of the expression must be absolute");
1472ec34544SRui Ueyama }
1482ec34544SRui Ueyama 
1492ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1502ec34544SRui Ueyama   moveAbsRight(A, B);
151a6acd23cSRafael Espindola   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
1522ec34544SRui Ueyama }
1532ec34544SRui Ueyama 
1542ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
15563a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1569cbb6dd1SRafael Espindola   if (!A.isAbsolute() && !B.isAbsolute())
1579cbb6dd1SRafael Espindola     return A.getValue() - B.getValue();
1584fbe3518SRui Ueyama   return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
1592ec34544SRui Ueyama }
1602ec34544SRui Ueyama 
1612ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1622ec34544SRui Ueyama   moveAbsRight(A, B);
1632ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
16441c7ab4aSGeorge Rimar           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
1652ec34544SRui Ueyama }
1662ec34544SRui Ueyama 
1672ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1682ec34544SRui Ueyama   moveAbsRight(A, B);
1692ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17041c7ab4aSGeorge Rimar           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
1712ec34544SRui Ueyama }
1722ec34544SRui Ueyama 
1732ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1748016bdfdSRafael Espindola   Config->HasDynamicList = true;
1752ec34544SRui Ueyama   expect("{");
176d72d97b3SRafael Espindola   std::vector<SymbolVersion> Locals;
177d72d97b3SRafael Espindola   std::vector<SymbolVersion> Globals;
178d72d97b3SRafael Espindola   std::tie(Locals, Globals) = readSymbols();
179d72d97b3SRafael Espindola   expect(";");
180d72d97b3SRafael Espindola 
181d72d97b3SRafael Espindola   if (!atEOF()) {
1822ec34544SRui Ueyama     setError("EOF expected, but got " + next());
183d72d97b3SRafael Espindola     return;
184d72d97b3SRafael Espindola   }
185d72d97b3SRafael Espindola   if (!Locals.empty()) {
186d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
187d72d97b3SRafael Espindola     return;
188d72d97b3SRafael Espindola   }
189d72d97b3SRafael Espindola 
190d72d97b3SRafael Espindola   for (SymbolVersion V : Globals)
191d72d97b3SRafael Espindola     Config->DynamicList.push_back(V);
1922ec34544SRui Ueyama }
1932ec34544SRui Ueyama 
1942ec34544SRui Ueyama void ScriptParser::readVersionScript() {
1952ec34544SRui Ueyama   readVersionScriptCommand();
1962ec34544SRui Ueyama   if (!atEOF())
1972ec34544SRui Ueyama     setError("EOF expected, but got " + next());
1982ec34544SRui Ueyama }
1992ec34544SRui Ueyama 
2002ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2012ec34544SRui Ueyama   if (consume("{")) {
2022ec34544SRui Ueyama     readAnonymousDeclaration();
2032ec34544SRui Ueyama     return;
2042ec34544SRui Ueyama   }
2052ec34544SRui Ueyama 
206b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2072ec34544SRui Ueyama     StringRef VerStr = next();
2082ec34544SRui Ueyama     if (VerStr == "{") {
2092ec34544SRui Ueyama       setError("anonymous version definition is used in "
2102ec34544SRui Ueyama                "combination with other version definitions");
2112ec34544SRui Ueyama       return;
2122ec34544SRui Ueyama     }
2132ec34544SRui Ueyama     expect("{");
2142ec34544SRui Ueyama     readVersionDeclaration(VerStr);
2152ec34544SRui Ueyama   }
2162ec34544SRui Ueyama }
2172ec34544SRui Ueyama 
2182ec34544SRui Ueyama void ScriptParser::readVersion() {
2192ec34544SRui Ueyama   expect("{");
2202ec34544SRui Ueyama   readVersionScriptCommand();
2212ec34544SRui Ueyama   expect("}");
2222ec34544SRui Ueyama }
2232ec34544SRui Ueyama 
2242ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2252ec34544SRui Ueyama   while (!atEOF()) {
2262ec34544SRui Ueyama     StringRef Tok = next();
2272ec34544SRui Ueyama     if (Tok == ";")
2282ec34544SRui Ueyama       continue;
2292ec34544SRui Ueyama 
230*d30a78b3SGeorge Rimar     if (Tok == "ENTRY") {
2312ec34544SRui Ueyama       readEntry();
2322ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2332ec34544SRui Ueyama       readExtern();
2341d92aa73SRui Ueyama     } else if (Tok == "GROUP") {
2352ec34544SRui Ueyama       readGroup();
2362ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2372ec34544SRui Ueyama       readInclude();
2381d92aa73SRui Ueyama     } else if (Tok == "INPUT") {
2391d92aa73SRui Ueyama       readInput();
2402ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2412ec34544SRui Ueyama       readMemory();
2422ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2432ec34544SRui Ueyama       readOutput();
2442ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2452ec34544SRui Ueyama       readOutputArch();
2462ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2472ec34544SRui Ueyama       readOutputFormat();
2482ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2492ec34544SRui Ueyama       readPhdrs();
2505f37541cSGeorge Rimar     } else if (Tok == "REGION_ALIAS") {
2515f37541cSGeorge Rimar       readRegionAlias();
2522ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2532ec34544SRui Ueyama       readSearchDir();
2542ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2552ec34544SRui Ueyama       readSections();
2562ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2572ec34544SRui Ueyama       readVersion();
258*d30a78b3SGeorge Rimar     } else if (SymbolAssignment *Cmd = readAssignment(Tok)) {
2596b394caaSRui Ueyama       Script->SectionCommands.push_back(Cmd);
2602ec34544SRui Ueyama     } else {
2612ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2622ec34544SRui Ueyama     }
2632ec34544SRui Ueyama   }
2642ec34544SRui Ueyama }
2652ec34544SRui Ueyama 
2668c7e8cceSPetr Hosek void ScriptParser::readDefsym(StringRef Name) {
2678c7e8cceSPetr Hosek   Expr E = readExpr();
2688c7e8cceSPetr Hosek   if (!atEOF())
2698c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
270e88b76a9SGeorge Rimar   SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
2718c7e8cceSPetr Hosek   Script->SectionCommands.push_back(Cmd);
2728c7e8cceSPetr Hosek }
2738c7e8cceSPetr Hosek 
2742ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2752ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2762ec34544SRui Ueyama     SmallString<128> PathData;
2772ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2782ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
279a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2802ec34544SRui Ueyama       return;
2812ec34544SRui Ueyama     }
2822ec34544SRui Ueyama   }
2832ec34544SRui Ueyama 
284875ae82bSRui Ueyama   if (S.startswith("/")) {
285a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2862ec34544SRui Ueyama   } else if (S.startswith("=")) {
2872ec34544SRui Ueyama     if (Config->Sysroot.empty())
288a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
2892ec34544SRui Ueyama     else
290a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
291a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
2922ec34544SRui Ueyama   } else if (S.startswith("-l")) {
2932ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
2942ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
295a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2962ec34544SRui Ueyama   } else {
2972ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
298a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
2992ec34544SRui Ueyama     else
3002ec34544SRui Ueyama       setError("unable to find " + S);
3012ec34544SRui Ueyama   }
3022ec34544SRui Ueyama }
3032ec34544SRui Ueyama 
3042ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3052ec34544SRui Ueyama   expect("(");
3062ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
3072ec34544SRui Ueyama   Config->AsNeeded = true;
308b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3092ec34544SRui Ueyama     addFile(unquote(next()));
3102ec34544SRui Ueyama   Config->AsNeeded = Orig;
3112ec34544SRui Ueyama }
3122ec34544SRui Ueyama 
3132ec34544SRui Ueyama void ScriptParser::readEntry() {
3142ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3152ec34544SRui Ueyama   expect("(");
3162ec34544SRui Ueyama   StringRef Tok = next();
3172ec34544SRui Ueyama   if (Config->Entry.empty())
3182ec34544SRui Ueyama     Config->Entry = Tok;
3192ec34544SRui Ueyama   expect(")");
3202ec34544SRui Ueyama }
3212ec34544SRui Ueyama 
3222ec34544SRui Ueyama void ScriptParser::readExtern() {
3232ec34544SRui Ueyama   expect("(");
324b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3252ec34544SRui Ueyama     Config->Undefined.push_back(next());
3262ec34544SRui Ueyama }
3272ec34544SRui Ueyama 
3282ec34544SRui Ueyama void ScriptParser::readGroup() {
3291d92aa73SRui Ueyama   bool Orig = InputFile::IsInGroup;
3301d92aa73SRui Ueyama   InputFile::IsInGroup = true;
3311d92aa73SRui Ueyama   readInput();
3321d92aa73SRui Ueyama   InputFile::IsInGroup = Orig;
333b72daf00SFangrui Song   if (!Orig)
334b72daf00SFangrui Song     ++InputFile::NextGroupId;
3352ec34544SRui Ueyama }
3362ec34544SRui Ueyama 
3372ec34544SRui Ueyama void ScriptParser::readInclude() {
3382ec34544SRui Ueyama   StringRef Tok = unquote(next());
3392ec34544SRui Ueyama 
3400440be4aSRui Ueyama   if (!Seen.insert(Tok).second) {
3410440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3420440be4aSRui Ueyama     return;
3430440be4aSRui Ueyama   }
3440440be4aSRui Ueyama 
3451de78471SAlexander Richardson   if (Optional<std::string> Path = searchLinkerScript(Tok)) {
3462ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3472ec34544SRui Ueyama       tokenize(*MB);
3482ec34544SRui Ueyama     return;
3492ec34544SRui Ueyama   }
3501de78471SAlexander Richardson   setError("cannot find linker script " + Tok);
3512ec34544SRui Ueyama }
3522ec34544SRui Ueyama 
3531d92aa73SRui Ueyama void ScriptParser::readInput() {
3541d92aa73SRui Ueyama   expect("(");
3551d92aa73SRui Ueyama   while (!errorCount() && !consume(")")) {
3561d92aa73SRui Ueyama     if (consume("AS_NEEDED"))
3571d92aa73SRui Ueyama       readAsNeeded();
3581d92aa73SRui Ueyama     else
3591d92aa73SRui Ueyama       addFile(unquote(next()));
3601d92aa73SRui Ueyama   }
3611d92aa73SRui Ueyama }
3621d92aa73SRui Ueyama 
3632ec34544SRui Ueyama void ScriptParser::readOutput() {
3642ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3652ec34544SRui Ueyama   expect("(");
3662ec34544SRui Ueyama   StringRef Tok = next();
3672ec34544SRui Ueyama   if (Config->OutputFile.empty())
3682ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3692ec34544SRui Ueyama   expect(")");
3702ec34544SRui Ueyama }
3712ec34544SRui Ueyama 
3722ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3732ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3742ec34544SRui Ueyama   expect("(");
375b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3762ec34544SRui Ueyama     skip();
3772ec34544SRui Ueyama }
3782ec34544SRui Ueyama 
3792ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3802ec34544SRui Ueyama   // Error checking only for now.
3812ec34544SRui Ueyama   expect("(");
3822ec34544SRui Ueyama   skip();
383b579c439SRui Ueyama   if (consume(")"))
3842ec34544SRui Ueyama     return;
385b579c439SRui Ueyama   expect(",");
3862ec34544SRui Ueyama   skip();
3872ec34544SRui Ueyama   expect(",");
3882ec34544SRui Ueyama   skip();
3892ec34544SRui Ueyama   expect(")");
3902ec34544SRui Ueyama }
3912ec34544SRui Ueyama 
3922ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3932ec34544SRui Ueyama   expect("{");
3942ec34544SRui Ueyama 
395b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
3960ae2c24cSRui Ueyama     PhdrsCommand Cmd;
3970ae2c24cSRui Ueyama     Cmd.Name = next();
3980ae2c24cSRui Ueyama     Cmd.Type = readPhdrType();
399b579c439SRui Ueyama 
400b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
401b579c439SRui Ueyama       if (consume("FILEHDR"))
4020ae2c24cSRui Ueyama         Cmd.HasFilehdr = true;
403b579c439SRui Ueyama       else if (consume("PHDRS"))
4040ae2c24cSRui Ueyama         Cmd.HasPhdrs = true;
405b579c439SRui Ueyama       else if (consume("AT"))
4060ae2c24cSRui Ueyama         Cmd.LMAExpr = readParenExpr();
407b579c439SRui Ueyama       else if (consume("FLAGS"))
4080ae2c24cSRui Ueyama         Cmd.Flags = readParenExpr()().getValue();
409b579c439SRui Ueyama       else
410b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
411b579c439SRui Ueyama     }
4120ae2c24cSRui Ueyama 
413ac27de9dSRui Ueyama     Script->PhdrsCommands.push_back(Cmd);
4142ec34544SRui Ueyama   }
4152ec34544SRui Ueyama }
4162ec34544SRui Ueyama 
4175f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4185f37541cSGeorge Rimar   expect("(");
4195f37541cSGeorge Rimar   StringRef Alias = unquote(next());
4205f37541cSGeorge Rimar   expect(",");
4215f37541cSGeorge Rimar   StringRef Name = next();
4225f37541cSGeorge Rimar   expect(")");
4235f37541cSGeorge Rimar 
424ac27de9dSRui Ueyama   if (Script->MemoryRegions.count(Alias))
4255f37541cSGeorge Rimar     setError("redefinition of memory region '" + Alias + "'");
426ac27de9dSRui Ueyama   if (!Script->MemoryRegions.count(Name))
4275f37541cSGeorge Rimar     setError("memory region '" + Name + "' is not defined");
4288c825db2SGeorge Rimar   Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
4295f37541cSGeorge Rimar }
4305f37541cSGeorge Rimar 
4312ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4322ec34544SRui Ueyama   expect("(");
4332ec34544SRui Ueyama   StringRef Tok = next();
4342ec34544SRui Ueyama   if (!Config->Nostdlib)
4352ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
4362ec34544SRui Ueyama   expect(")");
4372ec34544SRui Ueyama }
4382ec34544SRui Ueyama 
4392ec34544SRui Ueyama void ScriptParser::readSections() {
440a323e2a7SRui Ueyama   Script->HasSectionsCommand = true;
441b579c439SRui Ueyama 
4422ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
4432ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
4442ec34544SRui Ueyama   // script. See comment for computeFlags().
4452ec34544SRui Ueyama   Config->SingleRoRx = true;
4462ec34544SRui Ueyama 
4472ec34544SRui Ueyama   expect("{");
4489e2c8a9dSGeorge Rimar   std::vector<BaseCommand *> V;
449b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4502ec34544SRui Ueyama     StringRef Tok = next();
451*d30a78b3SGeorge Rimar     if (BaseCommand *Cmd = readAssignment(Tok))
4529e2c8a9dSGeorge Rimar       V.push_back(Cmd);
453*d30a78b3SGeorge Rimar     else
454*d30a78b3SGeorge Rimar       V.push_back(readOutputSectionDescription(Tok));
4552ec34544SRui Ueyama   }
4569e2c8a9dSGeorge Rimar 
4579e2c8a9dSGeorge Rimar   if (!atEOF() && consume("INSERT")) {
458796684b4SGeorge Rimar     std::vector<BaseCommand *> *Dest = nullptr;
459796684b4SGeorge Rimar     if (consume("AFTER"))
460796684b4SGeorge Rimar       Dest = &Script->InsertAfterCommands[next()];
461796684b4SGeorge Rimar     else if (consume("BEFORE"))
462796684b4SGeorge Rimar       Dest = &Script->InsertBeforeCommands[next()];
463796684b4SGeorge Rimar     else
464796684b4SGeorge Rimar       setError("expected AFTER/BEFORE, but got '" + next() + "'");
465796684b4SGeorge Rimar     if (Dest)
466796684b4SGeorge Rimar       Dest->insert(Dest->end(), V.begin(), V.end());
4679e2c8a9dSGeorge Rimar     return;
4689e2c8a9dSGeorge Rimar   }
4699e2c8a9dSGeorge Rimar 
4709e2c8a9dSGeorge Rimar   Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(),
4719e2c8a9dSGeorge Rimar                                  V.end());
4722ec34544SRui Ueyama }
4732ec34544SRui Ueyama 
4742ec34544SRui Ueyama static int precedence(StringRef Op) {
4752ec34544SRui Ueyama   return StringSwitch<int>(Op)
476aa92fca8SRui Ueyama       .Cases("*", "/", "%", 6)
477aa92fca8SRui Ueyama       .Cases("+", "-", 5)
478aa92fca8SRui Ueyama       .Cases("<<", ">>", 4)
479aa92fca8SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 3)
480aa92fca8SRui Ueyama       .Case("&", 2)
481aa92fca8SRui Ueyama       .Case("|", 1)
4822ec34544SRui Ueyama       .Default(-1);
4832ec34544SRui Ueyama }
4842ec34544SRui Ueyama 
4852ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4862ec34544SRui Ueyama   std::vector<StringRef> V;
487b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4882ec34544SRui Ueyama     V.push_back(next());
4892ec34544SRui Ueyama   return StringMatcher(V);
4902ec34544SRui Ueyama }
4912ec34544SRui Ueyama 
4922ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
4932ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
4942ec34544SRui Ueyama     return SortSectionPolicy::Name;
4952ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
4962ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
4972ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
4982ec34544SRui Ueyama     return SortSectionPolicy::Priority;
4992ec34544SRui Ueyama   if (consume("SORT_NONE"))
5002ec34544SRui Ueyama     return SortSectionPolicy::None;
5012ec34544SRui Ueyama   return SortSectionPolicy::Default;
5022ec34544SRui Ueyama }
5032ec34544SRui Ueyama 
50403fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
50503fc8d1eSRui Ueyama //
50603fc8d1eSRui Ueyama // <contents> ::= <elem>*
50703fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
50803fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
50903fc8d1eSRui Ueyama //
51003fc8d1eSRui Ueyama // For example,
51103fc8d1eSRui Ueyama //
51203fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
51303fc8d1eSRui Ueyama //
51403fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
51503fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
51603fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
5172ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
5182ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
519b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
5202ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
5212ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
5222ec34544SRui Ueyama       expect("(");
5232ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
5242ec34544SRui Ueyama     }
5252ec34544SRui Ueyama 
5262ec34544SRui Ueyama     std::vector<StringRef> V;
527b8a59c8aSBob Haarman     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
5282ec34544SRui Ueyama       V.push_back(next());
5292ec34544SRui Ueyama 
5302ec34544SRui Ueyama     if (!V.empty())
5312ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
5322ec34544SRui Ueyama     else
5332ec34544SRui Ueyama       setError("section pattern is expected");
5342ec34544SRui Ueyama   }
5352ec34544SRui Ueyama   return Ret;
5362ec34544SRui Ueyama }
5372ec34544SRui Ueyama 
5382ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
5392ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
5402ec34544SRui Ueyama //
5412ec34544SRui Ueyama // <patterns> ::= <section-list>
5422ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
5432ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
5442ec34544SRui Ueyama //
5452ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
5462ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
5472ec34544SRui Ueyama //
5482ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
5492ec34544SRui Ueyama InputSectionDescription *
5502ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
5512ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
5522ec34544SRui Ueyama   expect("(");
5532ec34544SRui Ueyama 
554b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
5552ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
5562ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
5572ec34544SRui Ueyama     std::vector<SectionPattern> V;
5582ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
5592ec34544SRui Ueyama       expect("(");
5602ec34544SRui Ueyama       Inner = readSortKind();
5612ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
5622ec34544SRui Ueyama         expect("(");
5632ec34544SRui Ueyama         V = readInputSectionsList();
5642ec34544SRui Ueyama         expect(")");
5652ec34544SRui Ueyama       } else {
5662ec34544SRui Ueyama         V = readInputSectionsList();
5672ec34544SRui Ueyama       }
5682ec34544SRui Ueyama       expect(")");
5692ec34544SRui Ueyama     } else {
5702ec34544SRui Ueyama       V = readInputSectionsList();
5712ec34544SRui Ueyama     }
5722ec34544SRui Ueyama 
5732ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5742ec34544SRui Ueyama       Pat.SortInner = Inner;
5752ec34544SRui Ueyama       Pat.SortOuter = Outer;
5762ec34544SRui Ueyama     }
5772ec34544SRui Ueyama 
5782ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5792ec34544SRui Ueyama   }
5802ec34544SRui Ueyama   return Cmd;
5812ec34544SRui Ueyama }
5822ec34544SRui Ueyama 
5832ec34544SRui Ueyama InputSectionDescription *
5842ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5852ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5862ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5872ec34544SRui Ueyama   if (Tok == "KEEP") {
5882ec34544SRui Ueyama     expect("(");
5892ec34544SRui Ueyama     StringRef FilePattern = next();
5902ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5912ec34544SRui Ueyama     expect(")");
592ac27de9dSRui Ueyama     Script->KeptSections.push_back(Cmd);
5932ec34544SRui Ueyama     return Cmd;
5942ec34544SRui Ueyama   }
5952ec34544SRui Ueyama   return readInputSectionRules(Tok);
5962ec34544SRui Ueyama }
5972ec34544SRui Ueyama 
5982ec34544SRui Ueyama void ScriptParser::readSort() {
5992ec34544SRui Ueyama   expect("(");
6002ec34544SRui Ueyama   expect("CONSTRUCTORS");
6012ec34544SRui Ueyama   expect(")");
6022ec34544SRui Ueyama }
6032ec34544SRui Ueyama 
604*d30a78b3SGeorge Rimar Expr ScriptParser::readAssert() {
6052ec34544SRui Ueyama   expect("(");
6062ec34544SRui Ueyama   Expr E = readExpr();
6072ec34544SRui Ueyama   expect(",");
6082ec34544SRui Ueyama   StringRef Msg = unquote(next());
6092ec34544SRui Ueyama   expect(")");
610b579c439SRui Ueyama 
6112ec34544SRui Ueyama   return [=] {
6122ec34544SRui Ueyama     if (!E().getValue())
6132ec34544SRui Ueyama       error(Msg);
6142ec34544SRui Ueyama     return Script->getDot();
6152ec34544SRui Ueyama   };
6162ec34544SRui Ueyama }
6172ec34544SRui Ueyama 
6182ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
6192ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
6202ec34544SRui Ueyama // what GNU linkers do.
6212ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
6222ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
6232ec34544SRui Ueyama   expect("(");
6248acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
6252ec34544SRui Ueyama   expect(")");
6262ec34544SRui Ueyama   return V;
6272ec34544SRui Ueyama }
6282ec34544SRui Ueyama 
6291c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
6301c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
6311c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
6323271d370SRui Ueyama //
6333271d370SRui Ueyama // An output section name can be followed by an address expression
6341c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
63597f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
6361c08e9f5SGeorge Rimar // of directive.
6373271d370SRui Ueyama //
638b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
639fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
6408c022ca7SRafael Espindola void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
6413271d370SRui Ueyama   if (consume("(")) {
6423271d370SRui Ueyama     if (consume("NOLOAD")) {
6433271d370SRui Ueyama       expect(")");
6443271d370SRui Ueyama       Cmd->Noload = true;
6453271d370SRui Ueyama       return;
6463271d370SRui Ueyama     }
6471c08e9f5SGeorge Rimar     if (consume("COPY") || consume("INFO") || consume("OVERLAY")) {
6481c08e9f5SGeorge Rimar       expect(")");
6491c08e9f5SGeorge Rimar       Cmd->NonAlloc = true;
6501c08e9f5SGeorge Rimar       return;
6511c08e9f5SGeorge Rimar     }
6523271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6533271d370SRui Ueyama     expect(")");
6543271d370SRui Ueyama   } else {
6553271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6563271d370SRui Ueyama   }
6573271d370SRui Ueyama 
658fbb0463fSGeorge Rimar   if (consume("(")) {
659fbb0463fSGeorge Rimar     expect("NOLOAD");
660fbb0463fSGeorge Rimar     expect(")");
661fbb0463fSGeorge Rimar     Cmd->Noload = true;
662fbb0463fSGeorge Rimar   }
663fbb0463fSGeorge Rimar }
664fbb0463fSGeorge Rimar 
665f22ec9ddSGeorge Rimar static Expr checkAlignment(Expr E, std::string &Loc) {
666f22ec9ddSGeorge Rimar   return [=] {
667f22ec9ddSGeorge Rimar     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
668f22ec9ddSGeorge Rimar     if (!isPowerOf2_64(Alignment)) {
669f22ec9ddSGeorge Rimar       error(Loc + ": alignment must be power of 2");
670f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
671f22ec9ddSGeorge Rimar     }
672f22ec9ddSGeorge Rimar     return Alignment;
673f22ec9ddSGeorge Rimar   };
674f22ec9ddSGeorge Rimar }
675f22ec9ddSGeorge Rimar 
6768c022ca7SRafael Espindola OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
6778c022ca7SRafael Espindola   OutputSection *Cmd =
6788c022ca7SRafael Espindola       Script->createOutputSection(OutSec, getCurrentLocation());
6793271d370SRui Ueyama 
680c4df670dSGeorge Rimar   size_t SymbolsReferenced = Script->ReferencedSymbols.size();
681c4df670dSGeorge Rimar 
6823271d370SRui Ueyama   if (peek() != ":")
6833271d370SRui Ueyama     readSectionAddressType(Cmd);
6842ec34544SRui Ueyama   expect(":");
6852ec34544SRui Ueyama 
686f22ec9ddSGeorge Rimar   std::string Location = getCurrentLocation();
6872ec34544SRui Ueyama   if (consume("AT"))
6882ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
6892ec34544SRui Ueyama   if (consume("ALIGN"))
690f22ec9ddSGeorge Rimar     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
6912ec34544SRui Ueyama   if (consume("SUBALIGN"))
692f22ec9ddSGeorge Rimar     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
6932ec34544SRui Ueyama 
6942ec34544SRui Ueyama   // Parse constraints.
6952ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
6962ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
6972ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
6982ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
6992ec34544SRui Ueyama   expect("{");
7002ec34544SRui Ueyama 
701b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
7022ec34544SRui Ueyama     StringRef Tok = next();
7032ec34544SRui Ueyama     if (Tok == ";") {
7042ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
705*d30a78b3SGeorge Rimar     } else if (SymbolAssignment *Assign = readAssignment(Tok)) {
7066b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Assign);
707f0403c60SRui Ueyama     } else if (ByteCommand *Data = readByteCommand(Tok)) {
7086b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Data);
7092ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
7102ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
7112ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
7122ec34544SRui Ueyama       // For ELF, we should ignore.
7132ec34544SRui Ueyama     } else if (Tok == "FILL") {
7142ec34544SRui Ueyama       Cmd->Filler = readFill();
7152ec34544SRui Ueyama     } else if (Tok == "SORT") {
7162ec34544SRui Ueyama       readSort();
7172ec34544SRui Ueyama     } else if (peek() == "(") {
7186b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
7192ec34544SRui Ueyama     } else {
7202ec34544SRui Ueyama       setError("unknown command " + Tok);
7212ec34544SRui Ueyama     }
7222ec34544SRui Ueyama   }
7232ec34544SRui Ueyama 
7242ec34544SRui Ueyama   if (consume(">"))
7252ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
7262ec34544SRui Ueyama 
7275d01a8beSGeorge Rimar   if (consume("AT")) {
7285d01a8beSGeorge Rimar     expect(">");
7295d01a8beSGeorge Rimar     Cmd->LMARegionName = next();
7305d01a8beSGeorge Rimar   }
7315d01a8beSGeorge Rimar 
7325d01a8beSGeorge Rimar   if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
7335d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
7345d01a8beSGeorge Rimar 
7352ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
7362ec34544SRui Ueyama 
7372ec34544SRui Ueyama   if (consume("="))
7388acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
7392ec34544SRui Ueyama   else if (peek().startswith("="))
7408acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
7412ec34544SRui Ueyama 
7422ec34544SRui Ueyama   // Consume optional comma following output section command.
7432ec34544SRui Ueyama   consume(",");
7442ec34544SRui Ueyama 
745c4df670dSGeorge Rimar   if (Script->ReferencedSymbols.size() > SymbolsReferenced)
746c4df670dSGeorge Rimar     Cmd->ExpressionsUseSymbols = true;
7472ec34544SRui Ueyama   return Cmd;
7482ec34544SRui Ueyama }
7492ec34544SRui Ueyama 
7508acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
7518acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
7522ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
7532ec34544SRui Ueyama //
7548acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
7558acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
7568acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
7578acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
758b58079d4SRui Ueyama   uint32_t V = 0;
759ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
7602ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
761b58079d4SRui Ueyama 
762b58079d4SRui Ueyama   uint32_t Buf;
763b58079d4SRui Ueyama   write32be(&Buf, V);
764b58079d4SRui Ueyama   return Buf;
7652ec34544SRui Ueyama }
7662ec34544SRui Ueyama 
7672ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
7682ec34544SRui Ueyama   expect("(");
769*d30a78b3SGeorge Rimar   SymbolAssignment *Cmd = readSymbolAssignment(next());
7702ec34544SRui Ueyama   Cmd->Provide = Provide;
7712ec34544SRui Ueyama   Cmd->Hidden = Hidden;
7722ec34544SRui Ueyama   expect(")");
7732ec34544SRui Ueyama   return Cmd;
7742ec34544SRui Ueyama }
7752ec34544SRui Ueyama 
776*d30a78b3SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Tok) {
777*d30a78b3SGeorge Rimar   // Assert expression returns Dot, so this is equal to ".=."
778*d30a78b3SGeorge Rimar   if (Tok == "ASSERT")
779*d30a78b3SGeorge Rimar     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
780*d30a78b3SGeorge Rimar 
781e88b76a9SGeorge Rimar   size_t OldPos = Pos;
7822ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
783e88b76a9SGeorge Rimar   if (peek() == "=" || peek() == "+=")
784*d30a78b3SGeorge Rimar     Cmd = readSymbolAssignment(Tok);
785e88b76a9SGeorge Rimar   else if (Tok == "PROVIDE")
7862ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
787e88b76a9SGeorge Rimar   else if (Tok == "HIDDEN")
7882ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
789e88b76a9SGeorge Rimar   else if (Tok == "PROVIDE_HIDDEN")
7902ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
791e88b76a9SGeorge Rimar 
792e88b76a9SGeorge Rimar   if (Cmd) {
793e88b76a9SGeorge Rimar     Cmd->CommandString =
794e88b76a9SGeorge Rimar         Tok.str() + " " +
795e88b76a9SGeorge Rimar         llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
796e88b76a9SGeorge Rimar     expect(";");
7972ec34544SRui Ueyama   }
7982ec34544SRui Ueyama   return Cmd;
7992ec34544SRui Ueyama }
8002ec34544SRui Ueyama 
801*d30a78b3SGeorge Rimar SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
8022ec34544SRui Ueyama   StringRef Op = next();
8032ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
8042ec34544SRui Ueyama   Expr E = readExpr();
8052ec34544SRui Ueyama   if (Op == "+=") {
8062ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
807722221f5SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
8082ec34544SRui Ueyama   }
809e88b76a9SGeorge Rimar   return make<SymbolAssignment>(Name, E, getCurrentLocation());
8102ec34544SRui Ueyama }
8112ec34544SRui Ueyama 
8122ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
8132ec34544SRui Ueyama // script expression.
8142ec34544SRui Ueyama Expr ScriptParser::readExpr() {
8152ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
8162ec34544SRui Ueyama   // they apply different tokenization rules.
8172ec34544SRui Ueyama   bool Orig = InExpr;
8182ec34544SRui Ueyama   InExpr = true;
8192ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
8202ec34544SRui Ueyama   InExpr = Orig;
8212ec34544SRui Ueyama   return E;
8222ec34544SRui Ueyama }
8232ec34544SRui Ueyama 
8247b91e213SGeorge Rimar Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
8252ec34544SRui Ueyama   if (Op == "+")
8262ec34544SRui Ueyama     return [=] { return add(L(), R()); };
8272ec34544SRui Ueyama   if (Op == "-")
8282ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
829b579c439SRui Ueyama   if (Op == "*")
8301d20222aSRui Ueyama     return [=] { return L().getValue() * R().getValue(); };
8317b91e213SGeorge Rimar   if (Op == "/") {
8327b91e213SGeorge Rimar     std::string Loc = getCurrentLocation();
8337b91e213SGeorge Rimar     return [=]() -> uint64_t {
8347b91e213SGeorge Rimar       if (uint64_t RV = R().getValue())
8357b91e213SGeorge Rimar         return L().getValue() / RV;
8367b91e213SGeorge Rimar       error(Loc + ": division by zero");
837067617f9SRui Ueyama       return 0;
8387b91e213SGeorge Rimar     };
8397b91e213SGeorge Rimar   }
8407b91e213SGeorge Rimar   if (Op == "%") {
8417b91e213SGeorge Rimar     std::string Loc = getCurrentLocation();
8427b91e213SGeorge Rimar     return [=]() -> uint64_t {
8437b91e213SGeorge Rimar       if (uint64_t RV = R().getValue())
8447b91e213SGeorge Rimar         return L().getValue() % RV;
8457b91e213SGeorge Rimar       error(Loc + ": modulo by zero");
846067617f9SRui Ueyama       return 0;
8477b91e213SGeorge Rimar     };
8487b91e213SGeorge Rimar   }
8492ec34544SRui Ueyama   if (Op == "<<")
8507e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
8512ec34544SRui Ueyama   if (Op == ">>")
8527e915511SRui Ueyama     return [=] { return L().getValue() >> R().getValue(); };
8532ec34544SRui Ueyama   if (Op == "<")
8542ec34544SRui Ueyama     return [=] { return L().getValue() < R().getValue(); };
8552ec34544SRui Ueyama   if (Op == ">")
8562ec34544SRui Ueyama     return [=] { return L().getValue() > R().getValue(); };
8572ec34544SRui Ueyama   if (Op == ">=")
8582ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
8592ec34544SRui Ueyama   if (Op == "<=")
8602ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
8612ec34544SRui Ueyama   if (Op == "==")
8622ec34544SRui 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 bitAnd(L(), R()); };
8672ec34544SRui Ueyama   if (Op == "|")
8682ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
8692ec34544SRui Ueyama   llvm_unreachable("invalid operator");
8702ec34544SRui Ueyama }
8712ec34544SRui Ueyama 
8722ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
8732ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
8742ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
875b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
8762ec34544SRui Ueyama     // Read an operator and an expression.
8772ec34544SRui Ueyama     if (consume("?"))
8782ec34544SRui Ueyama       return readTernary(Lhs);
8792ec34544SRui Ueyama     StringRef Op1 = peek();
8802ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
8812ec34544SRui Ueyama       break;
8822ec34544SRui Ueyama     skip();
8832ec34544SRui Ueyama     Expr Rhs = readPrimary();
8842ec34544SRui Ueyama 
8852ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
8862ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
8872ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
8882ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
8892ec34544SRui Ueyama     while (!atEOF()) {
8902ec34544SRui Ueyama       StringRef Op2 = peek();
8912ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
8922ec34544SRui Ueyama         break;
8932ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
8942ec34544SRui Ueyama     }
8952ec34544SRui Ueyama 
8962ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
8972ec34544SRui Ueyama   }
8982ec34544SRui Ueyama   return Lhs;
8992ec34544SRui Ueyama }
9002ec34544SRui Ueyama 
9015fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
9025fb17128SGeorge Rimar   std::string Location = getCurrentLocation();
9035fb17128SGeorge Rimar   return [=]() -> uint64_t {
9045fb17128SGeorge Rimar     if (Target)
9052ec34544SRui Ueyama       return Target->PageSize;
9065fb17128SGeorge Rimar     error(Location + ": unable to calculate page size");
9075fb17128SGeorge Rimar     return 4096; // Return a dummy value.
9085fb17128SGeorge Rimar   };
9095fb17128SGeorge Rimar }
9105fb17128SGeorge Rimar 
9115fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
9125fb17128SGeorge Rimar   StringRef S = readParenLiteral();
9135fb17128SGeorge Rimar   if (S == "COMMONPAGESIZE")
9145fb17128SGeorge Rimar     return getPageSize();
9152ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
9165fb17128SGeorge Rimar     return [] { return Config->MaxPageSize; };
9175fb17128SGeorge Rimar   setError("unknown constant: " + S);
918b068b037SGeorge Rimar   return [] { return 0; };
9192ec34544SRui Ueyama }
9202ec34544SRui Ueyama 
9215c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
9225c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
9235c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
9245c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
9252ec34544SRui Ueyama   // Hexadecimal
9265c65088fSRui Ueyama   uint64_t Val;
9274092016bSRui Ueyama   if (Tok.startswith_lower("0x")) {
9284092016bSRui Ueyama     if (!to_integer(Tok.substr(2), Val, 16))
9294092016bSRui Ueyama       return None;
9305c65088fSRui Ueyama     return Val;
9314092016bSRui Ueyama   }
9324092016bSRui Ueyama   if (Tok.endswith_lower("H")) {
9334092016bSRui Ueyama     if (!to_integer(Tok.drop_back(), Val, 16))
9344092016bSRui Ueyama       return None;
9355c65088fSRui Ueyama     return Val;
9364092016bSRui Ueyama   }
9372ec34544SRui Ueyama 
9382ec34544SRui Ueyama   // Decimal
9392ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
940ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9415c65088fSRui Ueyama       return None;
9425c65088fSRui Ueyama     return Val * 1024;
9432ec34544SRui Ueyama   }
9445c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
945ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9465c65088fSRui Ueyama       return None;
9475c65088fSRui Ueyama     return Val * 1024 * 1024;
9485c65088fSRui Ueyama   }
949ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
9505c65088fSRui Ueyama     return None;
9515c65088fSRui Ueyama   return Val;
9522ec34544SRui Ueyama }
9532ec34544SRui Ueyama 
954f0403c60SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
955b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
9562ec34544SRui Ueyama                  .Case("BYTE", 1)
9572ec34544SRui Ueyama                  .Case("SHORT", 2)
9582ec34544SRui Ueyama                  .Case("LONG", 4)
9592ec34544SRui Ueyama                  .Case("QUAD", 8)
9602ec34544SRui Ueyama                  .Default(-1);
9612ec34544SRui Ueyama   if (Size == -1)
9622ec34544SRui Ueyama     return nullptr;
96384bcabcbSGeorge Rimar 
96484bcabcbSGeorge Rimar   size_t OldPos = Pos;
96584bcabcbSGeorge Rimar   Expr E = readParenExpr();
96684bcabcbSGeorge Rimar   std::string CommandString =
96784bcabcbSGeorge Rimar       Tok.str() + " " +
96884bcabcbSGeorge Rimar       llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
96984bcabcbSGeorge Rimar   return make<ByteCommand>(E, Size, CommandString);
9702ec34544SRui Ueyama }
9712ec34544SRui Ueyama 
9722ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
9732ec34544SRui Ueyama   expect("(");
9745e9c7762SRafael Espindola   bool Orig = InExpr;
9755e9c7762SRafael Espindola   InExpr = false;
9762ec34544SRui Ueyama   StringRef Tok = next();
9775e9c7762SRafael Espindola   InExpr = Orig;
9782ec34544SRui Ueyama   expect(")");
9792ec34544SRui Ueyama   return Tok;
9802ec34544SRui Ueyama }
9812ec34544SRui Ueyama 
982617e2f98SRui Ueyama static void checkIfExists(OutputSection *Cmd, StringRef Location) {
98305c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
98405c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
98505c4f67cSRafael Espindola }
98605c4f67cSRafael Espindola 
9872ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
9882ec34544SRui Ueyama   if (peek() == "(")
9892ec34544SRui Ueyama     return readParenExpr();
9902ec34544SRui Ueyama 
9915c65088fSRui Ueyama   if (consume("~")) {
9922ec34544SRui Ueyama     Expr E = readPrimary();
993b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
9942ec34544SRui Ueyama   }
9956f1d954eSHafiz Abid Qadeer   if (consume("!")) {
9966f1d954eSHafiz Abid Qadeer     Expr E = readPrimary();
9976f1d954eSHafiz Abid Qadeer     return [=] { return !E().getValue(); };
9986f1d954eSHafiz Abid Qadeer   }
9995c65088fSRui Ueyama   if (consume("-")) {
10002ec34544SRui Ueyama     Expr E = readPrimary();
1001b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
10022ec34544SRui Ueyama   }
10032ec34544SRui Ueyama 
10045c65088fSRui Ueyama   StringRef Tok = next();
10055c65088fSRui Ueyama   std::string Location = getCurrentLocation();
10065c65088fSRui Ueyama 
10072ec34544SRui Ueyama   // Built-in functions are parsed here.
10082ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
10092ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
10102ec34544SRui Ueyama     Expr Inner = readParenExpr();
10112ec34544SRui Ueyama     return [=] {
10122ec34544SRui Ueyama       ExprValue I = Inner();
10132ec34544SRui Ueyama       I.ForceAbsolute = true;
10142ec34544SRui Ueyama       return I;
10152ec34544SRui Ueyama     };
10162ec34544SRui Ueyama   }
10172ec34544SRui Ueyama   if (Tok == "ADDR") {
10182ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10194fbe3518SRui Ueyama     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
102041c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
10214fbe3518SRui Ueyama       checkIfExists(Sec, Location);
10224fbe3518SRui Ueyama       return {Sec, false, 0, Location};
102341c7ab4aSGeorge Rimar     };
10242ec34544SRui Ueyama   }
10252ec34544SRui Ueyama   if (Tok == "ALIGN") {
10262ec34544SRui Ueyama     expect("(");
10272ec34544SRui Ueyama     Expr E = readExpr();
1028f22ec9ddSGeorge Rimar     if (consume(")")) {
1029f22ec9ddSGeorge Rimar       E = checkAlignment(E, Location);
1030f22ec9ddSGeorge Rimar       return [=] { return alignTo(Script->getDot(), E().getValue()); };
1031f22ec9ddSGeorge Rimar     }
1032b579c439SRui Ueyama     expect(",");
1033f22ec9ddSGeorge Rimar     Expr E2 = checkAlignment(readExpr(), Location);
10342ec34544SRui Ueyama     expect(")");
10353c6de1a6SPetr Hosek     return [=] {
10363c6de1a6SPetr Hosek       ExprValue V = E();
1037f22ec9ddSGeorge Rimar       V.Alignment = E2().getValue();
10383c6de1a6SPetr Hosek       return V;
10393c6de1a6SPetr Hosek     };
10402ec34544SRui Ueyama   }
10412ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
10422ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10438c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1044617e2f98SRui Ueyama     return [=] {
1045617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1046617e2f98SRui Ueyama       return Cmd->Alignment;
1047617e2f98SRui Ueyama     };
10482ec34544SRui Ueyama   }
10492ec34544SRui Ueyama   if (Tok == "ASSERT")
1050*d30a78b3SGeorge Rimar     return readAssert();
10515fb17128SGeorge Rimar   if (Tok == "CONSTANT")
10525fb17128SGeorge Rimar     return readConstant();
10532ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
10542ec34544SRui Ueyama     expect("(");
10552ec34544SRui Ueyama     Expr E = readExpr();
10562ec34544SRui Ueyama     expect(",");
10572ec34544SRui Ueyama     readExpr();
10582ec34544SRui Ueyama     expect(")");
105960833f6eSGeorge Rimar     return [=] {
106060833f6eSGeorge Rimar       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
106160833f6eSGeorge Rimar     };
10622ec34544SRui Ueyama   }
10632ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
10642ec34544SRui Ueyama     expect("(");
10652ec34544SRui Ueyama     expect(".");
10662ec34544SRui Ueyama     expect(")");
10672ec34544SRui Ueyama     return [] { return Script->getDot(); };
10682ec34544SRui Ueyama   }
10692ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
10702ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
10712ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
10722ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
10732ec34544SRui Ueyama     expect("(");
10742ec34544SRui Ueyama     readExpr();
10752ec34544SRui Ueyama     expect(",");
10762ec34544SRui Ueyama     readExpr();
10772ec34544SRui Ueyama     expect(")");
10785fb17128SGeorge Rimar     Expr E = getPageSize();
10795fb17128SGeorge Rimar     return [=] { return alignTo(Script->getDot(), E().getValue()); };
10802ec34544SRui Ueyama   }
10812ec34544SRui Ueyama   if (Tok == "DEFINED") {
10822ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10839b18f50fSRui Ueyama     return [=] { return Symtab->find(Name) ? 1 : 0; };
10842ec34544SRui Ueyama   }
108591b95b61SRui Ueyama   if (Tok == "LENGTH") {
108691b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1087b068b037SGeorge Rimar     if (Script->MemoryRegions.count(Name) == 0) {
108891b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1089b068b037SGeorge Rimar       return [] { return 0; };
1090b068b037SGeorge Rimar     }
1091ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Length; };
109291b95b61SRui Ueyama   }
10932ec34544SRui Ueyama   if (Tok == "LOADADDR") {
10942ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10958c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1096617e2f98SRui Ueyama     return [=] {
1097617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1098617e2f98SRui Ueyama       return Cmd->getLMA();
1099617e2f98SRui Ueyama     };
11002ec34544SRui Ueyama   }
1101fd11560fSGeorge Rimar   if (Tok == "MAX" || Tok == "MIN") {
1102fd11560fSGeorge Rimar     expect("(");
1103fd11560fSGeorge Rimar     Expr A = readExpr();
1104fd11560fSGeorge Rimar     expect(",");
1105fd11560fSGeorge Rimar     Expr B = readExpr();
1106fd11560fSGeorge Rimar     expect(")");
1107fd11560fSGeorge Rimar     if (Tok == "MIN")
1108fd11560fSGeorge Rimar       return [=] { return std::min(A().getValue(), B().getValue()); };
1109fd11560fSGeorge Rimar     return [=] { return std::max(A().getValue(), B().getValue()); };
1110fd11560fSGeorge Rimar   }
111191b95b61SRui Ueyama   if (Tok == "ORIGIN") {
111291b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1113b068b037SGeorge Rimar     if (Script->MemoryRegions.count(Name) == 0) {
111491b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1115b068b037SGeorge Rimar       return [] { return 0; };
1116b068b037SGeorge Rimar     }
1117ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Origin; };
111891b95b61SRui Ueyama   }
11192ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
11202ec34544SRui Ueyama     expect("(");
11212ec34544SRui Ueyama     skip();
11222ec34544SRui Ueyama     expect(",");
11232ec34544SRui Ueyama     Expr E = readExpr();
11242ec34544SRui Ueyama     expect(")");
11252ec34544SRui Ueyama     return [=] { return E(); };
11262ec34544SRui Ueyama   }
11272ec34544SRui Ueyama   if (Tok == "SIZEOF") {
11282ec34544SRui Ueyama     StringRef Name = readParenLiteral();
11298c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
113005c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
113105c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
113205c4f67cSRafael Espindola     // be empty.
11338c022ca7SRafael Espindola     return [=] { return Cmd->Size; };
11342ec34544SRui Ueyama   }
11352ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
11362ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
11372ec34544SRui Ueyama 
11384eb2eccbSRui Ueyama   // Tok is the dot.
11394eb2eccbSRui Ueyama   if (Tok == ".")
1140722221f5SRui Ueyama     return [=] { return Script->getSymbolValue(Tok, Location); };
11414eb2eccbSRui Ueyama 
11422ec34544SRui Ueyama   // Tok is a literal number.
11435c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11445c65088fSRui Ueyama     return [=] { return *Val; };
11452ec34544SRui Ueyama 
11462ec34544SRui Ueyama   // Tok is a symbol name.
11472ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
11482ec34544SRui Ueyama     setError("malformed number: " + Tok);
1149ac27de9dSRui Ueyama   Script->ReferencedSymbols.push_back(Tok);
1150722221f5SRui Ueyama   return [=] { return Script->getSymbolValue(Tok, Location); };
11512ec34544SRui Ueyama }
11522ec34544SRui Ueyama 
11532ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
11542ec34544SRui Ueyama   Expr L = readExpr();
11552ec34544SRui Ueyama   expect(":");
11562ec34544SRui Ueyama   Expr R = readExpr();
11572ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
11582ec34544SRui Ueyama }
11592ec34544SRui Ueyama 
11602ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
11612ec34544SRui Ueyama   expect("(");
11622ec34544SRui Ueyama   Expr E = readExpr();
11632ec34544SRui Ueyama   expect(")");
11642ec34544SRui Ueyama   return E;
11652ec34544SRui Ueyama }
11662ec34544SRui Ueyama 
11672ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
11682ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
1169b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
11702ec34544SRui Ueyama     StringRef Tok = next();
11712ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
11722ec34544SRui Ueyama   }
11732ec34544SRui Ueyama   return Phdrs;
11742ec34544SRui Ueyama }
11752ec34544SRui Ueyama 
11762ec34544SRui Ueyama // Read a program header type name. The next token must be a
11772ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
11782ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
11792ec34544SRui Ueyama   StringRef Tok = next();
11805c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11815c65088fSRui Ueyama     return *Val;
11822ec34544SRui Ueyama 
11832ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
11842ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
11852ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
11862ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
11872ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
11882ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
11892ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
11902ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
11912ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
11922ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
11932ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
11942ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
11952ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
11962ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
11972ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
11982ec34544SRui Ueyama                      .Default(-1);
11992ec34544SRui Ueyama 
12002ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
12012ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
12022ec34544SRui Ueyama     return PT_NULL;
12032ec34544SRui Ueyama   }
12042ec34544SRui Ueyama   return Ret;
12052ec34544SRui Ueyama }
12062ec34544SRui Ueyama 
12072ec34544SRui Ueyama // Reads an anonymous version declaration.
12082ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
12092ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12102ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12112ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
12122ec34544SRui Ueyama 
12132ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
12142ec34544SRui Ueyama     if (V.Name == "*")
12152ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
12162ec34544SRui Ueyama     else
12172ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
12182ec34544SRui Ueyama   }
12192ec34544SRui Ueyama 
12202ec34544SRui Ueyama   for (SymbolVersion V : Globals)
12212ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
12222ec34544SRui Ueyama 
12232ec34544SRui Ueyama   expect(";");
12242ec34544SRui Ueyama }
12252ec34544SRui Ueyama 
12262ec34544SRui Ueyama // Reads a non-anonymous version definition,
12272ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
12282ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
12292ec34544SRui Ueyama   // Read a symbol list.
12302ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12312ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12322ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
12332ec34544SRui Ueyama 
12342ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
12352ec34544SRui Ueyama     if (V.Name == "*")
12362ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
12372ec34544SRui Ueyama     else
12382ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
12392ec34544SRui Ueyama   }
12402ec34544SRui Ueyama 
12412ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
12422ec34544SRui Ueyama   VersionDefinition Ver;
12432ec34544SRui Ueyama   Ver.Name = VerStr;
12442ec34544SRui Ueyama   Ver.Globals = Globals;
12452ec34544SRui Ueyama 
12462ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
12472ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
12482ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
12492ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
12502ec34544SRui Ueyama 
12512ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
12522ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
12532ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
12542ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
12552ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
12562ec34544SRui Ueyama   if (peek() != ";")
12572ec34544SRui Ueyama     skip();
12582ec34544SRui Ueyama   expect(";");
12592ec34544SRui Ueyama }
12602ec34544SRui Ueyama 
12611e77ad14SRui Ueyama static bool hasWildcard(StringRef S) {
12621e77ad14SRui Ueyama   return S.find_first_of("?*[") != StringRef::npos;
12631e77ad14SRui Ueyama }
12641e77ad14SRui Ueyama 
12652ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
12662ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
12672ec34544SRui Ueyama ScriptParser::readSymbols() {
12682ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12692ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12702ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
12712ec34544SRui Ueyama 
1272b8a59c8aSBob Haarman   while (!errorCount()) {
12732ec34544SRui Ueyama     if (consume("}"))
12742ec34544SRui Ueyama       break;
12752ec34544SRui Ueyama     if (consumeLabel("local")) {
12762ec34544SRui Ueyama       V = &Locals;
12772ec34544SRui Ueyama       continue;
12782ec34544SRui Ueyama     }
12792ec34544SRui Ueyama     if (consumeLabel("global")) {
12802ec34544SRui Ueyama       V = &Globals;
12812ec34544SRui Ueyama       continue;
12822ec34544SRui Ueyama     }
12832ec34544SRui Ueyama 
12842ec34544SRui Ueyama     if (consume("extern")) {
12852ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
12862ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
12872ec34544SRui Ueyama     } else {
12882ec34544SRui Ueyama       StringRef Tok = next();
12892ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
12902ec34544SRui Ueyama     }
12912ec34544SRui Ueyama     expect(";");
12922ec34544SRui Ueyama   }
12932ec34544SRui Ueyama   return {Locals, Globals};
12942ec34544SRui Ueyama }
12952ec34544SRui Ueyama 
12962ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
12972ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
129817324d8bSRui Ueyama //
129917324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
130017324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
13012ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
13022ec34544SRui Ueyama   StringRef Tok = next();
13032ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
13042ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
13052ec34544SRui Ueyama     setError("Unknown language");
13062ec34544SRui Ueyama   expect("{");
13072ec34544SRui Ueyama 
13082ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
1309b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
13102ec34544SRui Ueyama     StringRef Tok = next();
13112ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
13122ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
131317324d8bSRui Ueyama     if (consume("}"))
131417324d8bSRui Ueyama       return Ret;
13152ec34544SRui Ueyama     expect(";");
13162ec34544SRui Ueyama   }
13172ec34544SRui Ueyama 
13182ec34544SRui Ueyama   expect("}");
13192ec34544SRui Ueyama   return Ret;
13202ec34544SRui Ueyama }
13212ec34544SRui Ueyama 
13222ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
13232ec34544SRui Ueyama                                             StringRef S3) {
1324b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
13252ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
13262ec34544SRui Ueyama     return 0;
13272ec34544SRui Ueyama   }
13282ec34544SRui Ueyama   expect("=");
1329040af7deSRui Ueyama   return readExpr()().getValue();
13302ec34544SRui Ueyama }
13312ec34544SRui Ueyama 
13322ec34544SRui Ueyama // Parse the MEMORY command as specified in:
13332ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
13342ec34544SRui Ueyama //
13352ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
13362ec34544SRui Ueyama void ScriptParser::readMemory() {
13372ec34544SRui Ueyama   expect("{");
1338b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
13392ec34544SRui Ueyama     StringRef Name = next();
13402ec34544SRui Ueyama 
13412ec34544SRui Ueyama     uint32_t Flags = 0;
13422ec34544SRui Ueyama     uint32_t NegFlags = 0;
13432ec34544SRui Ueyama     if (consume("(")) {
13442ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
13452ec34544SRui Ueyama       expect(")");
13462ec34544SRui Ueyama     }
13472ec34544SRui Ueyama     expect(":");
13482ec34544SRui Ueyama 
13492ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
13502ec34544SRui Ueyama     expect(",");
13512ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
13522ec34544SRui Ueyama 
13535f37541cSGeorge Rimar     // Add the memory region to the region map.
1354490f0a4dSRafael Espindola     MemoryRegion *MR =
1355490f0a4dSRafael Espindola         make<MemoryRegion>(Name, Origin, Length, Flags, NegFlags);
13560984cfa9SGeorge Rimar     if (!Script->MemoryRegions.insert({Name, MR}).second)
13570984cfa9SGeorge Rimar       setError("region '" + Name + "' already defined");
13582ec34544SRui Ueyama   }
13592ec34544SRui Ueyama }
13602ec34544SRui Ueyama 
13612ec34544SRui Ueyama // This function parses the attributes used to match against section
13622ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
13632ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
13642ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
13652ec34544SRui Ueyama   uint32_t Flags = 0;
13662ec34544SRui Ueyama   uint32_t NegFlags = 0;
13672ec34544SRui Ueyama   bool Invert = false;
13682ec34544SRui Ueyama 
13692ec34544SRui Ueyama   for (char C : next().lower()) {
13702ec34544SRui Ueyama     uint32_t Flag = 0;
13712ec34544SRui Ueyama     if (C == '!')
13722ec34544SRui Ueyama       Invert = !Invert;
13732ec34544SRui Ueyama     else if (C == 'w')
13742ec34544SRui Ueyama       Flag = SHF_WRITE;
13752ec34544SRui Ueyama     else if (C == 'x')
13762ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
13772ec34544SRui Ueyama     else if (C == 'a')
13782ec34544SRui Ueyama       Flag = SHF_ALLOC;
13792ec34544SRui Ueyama     else if (C != 'r')
13802ec34544SRui Ueyama       setError("invalid memory region attribute");
13812ec34544SRui Ueyama 
13822ec34544SRui Ueyama     if (Invert)
13832ec34544SRui Ueyama       NegFlags |= Flag;
13842ec34544SRui Ueyama     else
13852ec34544SRui Ueyama       Flags |= Flag;
13862ec34544SRui Ueyama   }
13872ec34544SRui Ueyama   return {Flags, NegFlags};
13882ec34544SRui Ueyama }
13892ec34544SRui Ueyama 
13902ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
13912ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
13922ec34544SRui Ueyama }
13932ec34544SRui Ueyama 
13942ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
13952ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
13962ec34544SRui Ueyama }
13972ec34544SRui Ueyama 
13982ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
13992ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
14002ec34544SRui Ueyama }
14018c7e8cceSPetr Hosek 
14028c7e8cceSPetr Hosek void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
14038c7e8cceSPetr Hosek   ScriptParser(MB).readDefsym(Name);
14048c7e8cceSPetr Hosek }
1405