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();
662ec34544SRui Ueyama   void readMemory();
672ec34544SRui Ueyama   void readOutput();
682ec34544SRui Ueyama   void readOutputArch();
692ec34544SRui Ueyama   void readOutputFormat();
702ec34544SRui Ueyama   void readPhdrs();
715f37541cSGeorge Rimar   void readRegionAlias();
722ec34544SRui Ueyama   void readSearchDir();
732ec34544SRui Ueyama   void readSections();
742ec34544SRui Ueyama   void readVersion();
752ec34544SRui Ueyama   void readVersionScriptCommand();
762ec34544SRui Ueyama 
772ec34544SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
78f0403c60SRui Ueyama   ByteCommand *readByteCommand(StringRef Tok);
792ec34544SRui Ueyama   uint32_t readFill();
808acbf1ccSRui Ueyama   uint32_t parseFill(StringRef Tok);
818c022ca7SRafael Espindola   void readSectionAddressType(OutputSection *Cmd);
828c022ca7SRafael Espindola   OutputSection *readOutputSectionDescription(StringRef OutSec);
832ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
842ec34544SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef Tok);
852ec34544SRui Ueyama   StringMatcher readFilePatterns();
862ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
872ec34544SRui Ueyama   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
882ec34544SRui Ueyama   unsigned readPhdrType();
892ec34544SRui Ueyama   SortSectionPolicy readSortKind();
902ec34544SRui Ueyama   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
912ec34544SRui Ueyama   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
922ec34544SRui Ueyama   void readSort();
9323af89ccSRui Ueyama   AssertCommand *readAssert();
9423af89ccSRui Ueyama   Expr readAssertExpr();
955fb17128SGeorge Rimar   Expr readConstant();
965fb17128SGeorge Rimar   Expr getPageSize();
972ec34544SRui Ueyama 
982ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
992ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1002ec34544SRui Ueyama 
1012ec34544SRui Ueyama   Expr readExpr();
1022ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1032ec34544SRui Ueyama   StringRef readParenLiteral();
1042ec34544SRui Ueyama   Expr readPrimary();
1052ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1062ec34544SRui Ueyama   Expr readParenExpr();
1072ec34544SRui Ueyama 
1082ec34544SRui Ueyama   // For parsing version script.
1092ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1102ec34544SRui Ueyama   void readAnonymousDeclaration();
1112ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1122ec34544SRui Ueyama 
1132ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1142ec34544SRui Ueyama   readSymbols();
1152ec34544SRui Ueyama 
116fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1172ec34544SRui Ueyama   bool IsUnderSysroot;
1180440be4aSRui Ueyama 
1190440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1200440be4aSRui Ueyama   StringSet<> Seen;
1212ec34544SRui Ueyama };
12296b3fe02SRui Ueyama } // namespace
1232ec34544SRui Ueyama 
1241e77ad14SRui Ueyama static StringRef unquote(StringRef S) {
1251e77ad14SRui Ueyama   if (S.startswith("\""))
1261e77ad14SRui Ueyama     return S.substr(1, S.size() - 2);
1271e77ad14SRui Ueyama   return S;
1281e77ad14SRui Ueyama }
1291e77ad14SRui Ueyama 
1302ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1312ec34544SRui Ueyama   if (Config->Sysroot == "")
1322ec34544SRui Ueyama     return false;
1332ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1342ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1352ec34544SRui Ueyama       return true;
1362ec34544SRui Ueyama   return false;
1372ec34544SRui Ueyama }
1382ec34544SRui Ueyama 
1392ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1402ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1412ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
14223be5e8dSRafael Espindola   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
1432ec34544SRui Ueyama     std::swap(A, B);
1442ec34544SRui Ueyama   if (!B.isAbsolute())
14541c7ab4aSGeorge Rimar     error(A.Loc + ": at least one side of the expression must be absolute");
1462ec34544SRui Ueyama }
1472ec34544SRui Ueyama 
1482ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1492ec34544SRui Ueyama   moveAbsRight(A, B);
150a6acd23cSRafael Espindola   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
1512ec34544SRui Ueyama }
1522ec34544SRui Ueyama 
1532ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
15463a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1559cbb6dd1SRafael Espindola   if (!A.isAbsolute() && !B.isAbsolute())
1569cbb6dd1SRafael Espindola     return A.getValue() - B.getValue();
1574fbe3518SRui Ueyama   return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
1582ec34544SRui Ueyama }
1592ec34544SRui Ueyama 
1602ec34544SRui Ueyama static ExprValue div(ExprValue A, ExprValue B) {
1612ec34544SRui Ueyama   if (uint64_t BV = B.getValue())
1622ec34544SRui Ueyama     return A.getValue() / BV;
1632ec34544SRui Ueyama   error("division by zero");
1642ec34544SRui Ueyama   return 0;
1652ec34544SRui Ueyama }
1662ec34544SRui Ueyama 
167*39ba31ffSRui Ueyama static ExprValue mod(ExprValue A, ExprValue B) {
168*39ba31ffSRui Ueyama   if (uint64_t BV = B.getValue())
169*39ba31ffSRui Ueyama     return A.getValue() % BV;
170*39ba31ffSRui Ueyama   error("modulo by zero");
171*39ba31ffSRui Ueyama   return 0;
172*39ba31ffSRui Ueyama }
173*39ba31ffSRui Ueyama 
1742ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1752ec34544SRui Ueyama   moveAbsRight(A, B);
1762ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17741c7ab4aSGeorge Rimar           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
1782ec34544SRui Ueyama }
1792ec34544SRui Ueyama 
1802ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1812ec34544SRui Ueyama   moveAbsRight(A, B);
1822ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
18341c7ab4aSGeorge Rimar           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
1842ec34544SRui Ueyama }
1852ec34544SRui Ueyama 
1862ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1878016bdfdSRafael Espindola   Config->HasDynamicList = true;
1882ec34544SRui Ueyama   expect("{");
189d72d97b3SRafael Espindola   std::vector<SymbolVersion> Locals;
190d72d97b3SRafael Espindola   std::vector<SymbolVersion> Globals;
191d72d97b3SRafael Espindola   std::tie(Locals, Globals) = readSymbols();
192d72d97b3SRafael Espindola   expect(";");
193d72d97b3SRafael Espindola 
194d72d97b3SRafael Espindola   if (!atEOF()) {
1952ec34544SRui Ueyama     setError("EOF expected, but got " + next());
196d72d97b3SRafael Espindola     return;
197d72d97b3SRafael Espindola   }
198d72d97b3SRafael Espindola   if (!Locals.empty()) {
199d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
200d72d97b3SRafael Espindola     return;
201d72d97b3SRafael Espindola   }
202d72d97b3SRafael Espindola 
203d72d97b3SRafael Espindola   for (SymbolVersion V : Globals)
204d72d97b3SRafael Espindola     Config->DynamicList.push_back(V);
2052ec34544SRui Ueyama }
2062ec34544SRui Ueyama 
2072ec34544SRui Ueyama void ScriptParser::readVersionScript() {
2082ec34544SRui Ueyama   readVersionScriptCommand();
2092ec34544SRui Ueyama   if (!atEOF())
2102ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2112ec34544SRui Ueyama }
2122ec34544SRui Ueyama 
2132ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2142ec34544SRui Ueyama   if (consume("{")) {
2152ec34544SRui Ueyama     readAnonymousDeclaration();
2162ec34544SRui Ueyama     return;
2172ec34544SRui Ueyama   }
2182ec34544SRui Ueyama 
219b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2202ec34544SRui Ueyama     StringRef VerStr = next();
2212ec34544SRui Ueyama     if (VerStr == "{") {
2222ec34544SRui Ueyama       setError("anonymous version definition is used in "
2232ec34544SRui Ueyama                "combination with other version definitions");
2242ec34544SRui Ueyama       return;
2252ec34544SRui Ueyama     }
2262ec34544SRui Ueyama     expect("{");
2272ec34544SRui Ueyama     readVersionDeclaration(VerStr);
2282ec34544SRui Ueyama   }
2292ec34544SRui Ueyama }
2302ec34544SRui Ueyama 
2312ec34544SRui Ueyama void ScriptParser::readVersion() {
2322ec34544SRui Ueyama   expect("{");
2332ec34544SRui Ueyama   readVersionScriptCommand();
2342ec34544SRui Ueyama   expect("}");
2352ec34544SRui Ueyama }
2362ec34544SRui Ueyama 
2372ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2382ec34544SRui Ueyama   while (!atEOF()) {
2392ec34544SRui Ueyama     StringRef Tok = next();
2402ec34544SRui Ueyama     if (Tok == ";")
2412ec34544SRui Ueyama       continue;
2422ec34544SRui Ueyama 
2432ec34544SRui Ueyama     if (Tok == "ASSERT") {
2446b394caaSRui Ueyama       Script->SectionCommands.push_back(readAssert());
2452ec34544SRui Ueyama     } else if (Tok == "ENTRY") {
2462ec34544SRui Ueyama       readEntry();
2472ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2482ec34544SRui Ueyama       readExtern();
2492ec34544SRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
2502ec34544SRui Ueyama       readGroup();
2512ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2522ec34544SRui Ueyama       readInclude();
2532ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2542ec34544SRui Ueyama       readMemory();
2552ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2562ec34544SRui Ueyama       readOutput();
2572ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2582ec34544SRui Ueyama       readOutputArch();
2592ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2602ec34544SRui Ueyama       readOutputFormat();
2612ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2622ec34544SRui Ueyama       readPhdrs();
2635f37541cSGeorge Rimar     } else if (Tok == "REGION_ALIAS") {
2645f37541cSGeorge Rimar       readRegionAlias();
2652ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2662ec34544SRui Ueyama       readSearchDir();
2672ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2682ec34544SRui Ueyama       readSections();
2692ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2702ec34544SRui Ueyama       readVersion();
2712ec34544SRui Ueyama     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
2726b394caaSRui Ueyama       Script->SectionCommands.push_back(Cmd);
2732ec34544SRui Ueyama     } else {
2742ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2752ec34544SRui Ueyama     }
2762ec34544SRui Ueyama   }
2772ec34544SRui Ueyama }
2782ec34544SRui Ueyama 
2798c7e8cceSPetr Hosek void ScriptParser::readDefsym(StringRef Name) {
2808c7e8cceSPetr Hosek   Expr E = readExpr();
2818c7e8cceSPetr Hosek   if (!atEOF())
2828c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
2838c7e8cceSPetr Hosek   SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
2848c7e8cceSPetr Hosek   Script->SectionCommands.push_back(Cmd);
2858c7e8cceSPetr Hosek }
2868c7e8cceSPetr Hosek 
2872ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2882ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2892ec34544SRui Ueyama     SmallString<128> PathData;
2902ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2912ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
292a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2932ec34544SRui Ueyama       return;
2942ec34544SRui Ueyama     }
2952ec34544SRui Ueyama   }
2962ec34544SRui Ueyama 
297875ae82bSRui Ueyama   if (S.startswith("/")) {
298a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2992ec34544SRui Ueyama   } else if (S.startswith("=")) {
3002ec34544SRui Ueyama     if (Config->Sysroot.empty())
301a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
3022ec34544SRui Ueyama     else
303a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
304a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
3052ec34544SRui Ueyama   } else if (S.startswith("-l")) {
3062ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
3072ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
308a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
3092ec34544SRui Ueyama   } else {
3102ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
311a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
3122ec34544SRui Ueyama     else
3132ec34544SRui Ueyama       setError("unable to find " + S);
3142ec34544SRui Ueyama   }
3152ec34544SRui Ueyama }
3162ec34544SRui Ueyama 
3172ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3182ec34544SRui Ueyama   expect("(");
3192ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
3202ec34544SRui Ueyama   Config->AsNeeded = true;
321b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3222ec34544SRui Ueyama     addFile(unquote(next()));
3232ec34544SRui Ueyama   Config->AsNeeded = Orig;
3242ec34544SRui Ueyama }
3252ec34544SRui Ueyama 
3262ec34544SRui Ueyama void ScriptParser::readEntry() {
3272ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3282ec34544SRui Ueyama   expect("(");
3292ec34544SRui Ueyama   StringRef Tok = next();
3302ec34544SRui Ueyama   if (Config->Entry.empty())
3312ec34544SRui Ueyama     Config->Entry = Tok;
3322ec34544SRui Ueyama   expect(")");
3332ec34544SRui Ueyama }
3342ec34544SRui Ueyama 
3352ec34544SRui Ueyama void ScriptParser::readExtern() {
3362ec34544SRui Ueyama   expect("(");
337b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3382ec34544SRui Ueyama     Config->Undefined.push_back(next());
3392ec34544SRui Ueyama }
3402ec34544SRui Ueyama 
3412ec34544SRui Ueyama void ScriptParser::readGroup() {
3422ec34544SRui Ueyama   expect("(");
343b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
344b579c439SRui Ueyama     if (consume("AS_NEEDED"))
3452ec34544SRui Ueyama       readAsNeeded();
3462ec34544SRui Ueyama     else
347b579c439SRui Ueyama       addFile(unquote(next()));
3482ec34544SRui Ueyama   }
3492ec34544SRui Ueyama }
3502ec34544SRui Ueyama 
3512ec34544SRui Ueyama void ScriptParser::readInclude() {
3522ec34544SRui Ueyama   StringRef Tok = unquote(next());
3532ec34544SRui Ueyama 
3540440be4aSRui Ueyama   if (!Seen.insert(Tok).second) {
3550440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3560440be4aSRui Ueyama     return;
3570440be4aSRui Ueyama   }
3580440be4aSRui Ueyama 
3591de78471SAlexander Richardson   if (Optional<std::string> Path = searchLinkerScript(Tok)) {
3602ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3612ec34544SRui Ueyama       tokenize(*MB);
3622ec34544SRui Ueyama     return;
3632ec34544SRui Ueyama   }
3641de78471SAlexander Richardson   setError("cannot find linker script " + Tok);
3652ec34544SRui Ueyama }
3662ec34544SRui Ueyama 
3672ec34544SRui Ueyama void ScriptParser::readOutput() {
3682ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3692ec34544SRui Ueyama   expect("(");
3702ec34544SRui Ueyama   StringRef Tok = next();
3712ec34544SRui Ueyama   if (Config->OutputFile.empty())
3722ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3732ec34544SRui Ueyama   expect(")");
3742ec34544SRui Ueyama }
3752ec34544SRui Ueyama 
3762ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3772ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3782ec34544SRui Ueyama   expect("(");
379b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3802ec34544SRui Ueyama     skip();
3812ec34544SRui Ueyama }
3822ec34544SRui Ueyama 
3832ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3842ec34544SRui Ueyama   // Error checking only for now.
3852ec34544SRui Ueyama   expect("(");
3862ec34544SRui Ueyama   skip();
387b579c439SRui Ueyama   if (consume(")"))
3882ec34544SRui Ueyama     return;
389b579c439SRui Ueyama   expect(",");
3902ec34544SRui Ueyama   skip();
3912ec34544SRui Ueyama   expect(",");
3922ec34544SRui Ueyama   skip();
3932ec34544SRui Ueyama   expect(")");
3942ec34544SRui Ueyama }
3952ec34544SRui Ueyama 
3962ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3972ec34544SRui Ueyama   expect("{");
3982ec34544SRui Ueyama 
399b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4000ae2c24cSRui Ueyama     PhdrsCommand Cmd;
4010ae2c24cSRui Ueyama     Cmd.Name = next();
4020ae2c24cSRui Ueyama     Cmd.Type = readPhdrType();
403b579c439SRui Ueyama 
404b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
405b579c439SRui Ueyama       if (consume("FILEHDR"))
4060ae2c24cSRui Ueyama         Cmd.HasFilehdr = true;
407b579c439SRui Ueyama       else if (consume("PHDRS"))
4080ae2c24cSRui Ueyama         Cmd.HasPhdrs = true;
409b579c439SRui Ueyama       else if (consume("AT"))
4100ae2c24cSRui Ueyama         Cmd.LMAExpr = readParenExpr();
411b579c439SRui Ueyama       else if (consume("FLAGS"))
4120ae2c24cSRui Ueyama         Cmd.Flags = readParenExpr()().getValue();
413b579c439SRui Ueyama       else
414b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
415b579c439SRui Ueyama     }
4160ae2c24cSRui Ueyama 
417ac27de9dSRui Ueyama     Script->PhdrsCommands.push_back(Cmd);
4182ec34544SRui Ueyama   }
4192ec34544SRui Ueyama }
4202ec34544SRui Ueyama 
4215f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4225f37541cSGeorge Rimar   expect("(");
4235f37541cSGeorge Rimar   StringRef Alias = unquote(next());
4245f37541cSGeorge Rimar   expect(",");
4255f37541cSGeorge Rimar   StringRef Name = next();
4265f37541cSGeorge Rimar   expect(")");
4275f37541cSGeorge Rimar 
428ac27de9dSRui Ueyama   if (Script->MemoryRegions.count(Alias))
4295f37541cSGeorge Rimar     setError("redefinition of memory region '" + Alias + "'");
430ac27de9dSRui Ueyama   if (!Script->MemoryRegions.count(Name))
4315f37541cSGeorge Rimar     setError("memory region '" + Name + "' is not defined");
4328c825db2SGeorge Rimar   Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
4335f37541cSGeorge Rimar }
4345f37541cSGeorge Rimar 
4352ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4362ec34544SRui Ueyama   expect("(");
4372ec34544SRui Ueyama   StringRef Tok = next();
4382ec34544SRui Ueyama   if (!Config->Nostdlib)
4392ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
4402ec34544SRui Ueyama   expect(")");
4412ec34544SRui Ueyama }
4422ec34544SRui Ueyama 
4432ec34544SRui Ueyama void ScriptParser::readSections() {
444a323e2a7SRui Ueyama   Script->HasSectionsCommand = true;
445b579c439SRui Ueyama 
4462ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
4472ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
4482ec34544SRui Ueyama   // script. See comment for computeFlags().
4492ec34544SRui Ueyama   Config->SingleRoRx = true;
4502ec34544SRui Ueyama 
4512ec34544SRui Ueyama   expect("{");
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     }
4616b394caaSRui Ueyama     Script->SectionCommands.push_back(Cmd);
4622ec34544SRui Ueyama   }
4632ec34544SRui Ueyama }
4642ec34544SRui Ueyama 
4652ec34544SRui Ueyama static int precedence(StringRef Op) {
4662ec34544SRui Ueyama   return StringSwitch<int>(Op)
467*39ba31ffSRui Ueyama       .Cases("*", "/", "%", 5)
4682ec34544SRui Ueyama       .Cases("+", "-", 4)
4692ec34544SRui Ueyama       .Cases("<<", ">>", 3)
4702ec34544SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
4712ec34544SRui Ueyama       .Cases("&", "|", 1)
4722ec34544SRui Ueyama       .Default(-1);
4732ec34544SRui Ueyama }
4742ec34544SRui Ueyama 
4752ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4762ec34544SRui Ueyama   std::vector<StringRef> V;
477b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4782ec34544SRui Ueyama     V.push_back(next());
4792ec34544SRui Ueyama   return StringMatcher(V);
4802ec34544SRui Ueyama }
4812ec34544SRui Ueyama 
4822ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
4832ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
4842ec34544SRui Ueyama     return SortSectionPolicy::Name;
4852ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
4862ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
4872ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
4882ec34544SRui Ueyama     return SortSectionPolicy::Priority;
4892ec34544SRui Ueyama   if (consume("SORT_NONE"))
4902ec34544SRui Ueyama     return SortSectionPolicy::None;
4912ec34544SRui Ueyama   return SortSectionPolicy::Default;
4922ec34544SRui Ueyama }
4932ec34544SRui Ueyama 
49403fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
49503fc8d1eSRui Ueyama //
49603fc8d1eSRui Ueyama // <contents> ::= <elem>*
49703fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
49803fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
49903fc8d1eSRui Ueyama //
50003fc8d1eSRui Ueyama // For example,
50103fc8d1eSRui Ueyama //
50203fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
50303fc8d1eSRui Ueyama //
50403fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
50503fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
50603fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
5072ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
5082ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
509b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
5102ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
5112ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
5122ec34544SRui Ueyama       expect("(");
5132ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
5142ec34544SRui Ueyama     }
5152ec34544SRui Ueyama 
5162ec34544SRui Ueyama     std::vector<StringRef> V;
517b8a59c8aSBob Haarman     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
5182ec34544SRui Ueyama       V.push_back(next());
5192ec34544SRui Ueyama 
5202ec34544SRui Ueyama     if (!V.empty())
5212ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
5222ec34544SRui Ueyama     else
5232ec34544SRui Ueyama       setError("section pattern is expected");
5242ec34544SRui Ueyama   }
5252ec34544SRui Ueyama   return Ret;
5262ec34544SRui Ueyama }
5272ec34544SRui Ueyama 
5282ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
5292ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
5302ec34544SRui Ueyama //
5312ec34544SRui Ueyama // <patterns> ::= <section-list>
5322ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
5332ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
5342ec34544SRui Ueyama //
5352ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
5362ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
5372ec34544SRui Ueyama //
5382ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
5392ec34544SRui Ueyama InputSectionDescription *
5402ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
5412ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
5422ec34544SRui Ueyama   expect("(");
5432ec34544SRui Ueyama 
544b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
5452ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
5462ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
5472ec34544SRui Ueyama     std::vector<SectionPattern> V;
5482ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
5492ec34544SRui Ueyama       expect("(");
5502ec34544SRui Ueyama       Inner = readSortKind();
5512ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
5522ec34544SRui Ueyama         expect("(");
5532ec34544SRui Ueyama         V = readInputSectionsList();
5542ec34544SRui Ueyama         expect(")");
5552ec34544SRui Ueyama       } else {
5562ec34544SRui Ueyama         V = readInputSectionsList();
5572ec34544SRui Ueyama       }
5582ec34544SRui Ueyama       expect(")");
5592ec34544SRui Ueyama     } else {
5602ec34544SRui Ueyama       V = readInputSectionsList();
5612ec34544SRui Ueyama     }
5622ec34544SRui Ueyama 
5632ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5642ec34544SRui Ueyama       Pat.SortInner = Inner;
5652ec34544SRui Ueyama       Pat.SortOuter = Outer;
5662ec34544SRui Ueyama     }
5672ec34544SRui Ueyama 
5682ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5692ec34544SRui Ueyama   }
5702ec34544SRui Ueyama   return Cmd;
5712ec34544SRui Ueyama }
5722ec34544SRui Ueyama 
5732ec34544SRui Ueyama InputSectionDescription *
5742ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5752ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5762ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5772ec34544SRui Ueyama   if (Tok == "KEEP") {
5782ec34544SRui Ueyama     expect("(");
5792ec34544SRui Ueyama     StringRef FilePattern = next();
5802ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5812ec34544SRui Ueyama     expect(")");
582ac27de9dSRui Ueyama     Script->KeptSections.push_back(Cmd);
5832ec34544SRui Ueyama     return Cmd;
5842ec34544SRui Ueyama   }
5852ec34544SRui Ueyama   return readInputSectionRules(Tok);
5862ec34544SRui Ueyama }
5872ec34544SRui Ueyama 
5882ec34544SRui Ueyama void ScriptParser::readSort() {
5892ec34544SRui Ueyama   expect("(");
5902ec34544SRui Ueyama   expect("CONSTRUCTORS");
5912ec34544SRui Ueyama   expect(")");
5922ec34544SRui Ueyama }
5932ec34544SRui Ueyama 
59423af89ccSRui Ueyama AssertCommand *ScriptParser::readAssert() {
59523af89ccSRui Ueyama   return make<AssertCommand>(readAssertExpr());
59623af89ccSRui Ueyama }
59723af89ccSRui Ueyama 
59823af89ccSRui Ueyama Expr ScriptParser::readAssertExpr() {
5992ec34544SRui Ueyama   expect("(");
6002ec34544SRui Ueyama   Expr E = readExpr();
6012ec34544SRui Ueyama   expect(",");
6022ec34544SRui Ueyama   StringRef Msg = unquote(next());
6032ec34544SRui Ueyama   expect(")");
604b579c439SRui Ueyama 
6052ec34544SRui Ueyama   return [=] {
6062ec34544SRui Ueyama     if (!E().getValue())
6072ec34544SRui Ueyama       error(Msg);
6082ec34544SRui Ueyama     return Script->getDot();
6092ec34544SRui Ueyama   };
6102ec34544SRui Ueyama }
6112ec34544SRui Ueyama 
6122ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
6132ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
6142ec34544SRui Ueyama // what GNU linkers do.
6152ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
6162ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
6172ec34544SRui Ueyama   expect("(");
6188acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
6192ec34544SRui Ueyama   expect(")");
6202ec34544SRui Ueyama   return V;
6212ec34544SRui Ueyama }
6222ec34544SRui Ueyama 
6231c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
6241c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
6251c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
6263271d370SRui Ueyama //
6273271d370SRui Ueyama // An output section name can be followed by an address expression
6281c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
62997f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
6301c08e9f5SGeorge Rimar // of directive.
6313271d370SRui Ueyama //
632b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
633fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
6348c022ca7SRafael Espindola void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
6353271d370SRui Ueyama   if (consume("(")) {
6363271d370SRui Ueyama     if (consume("NOLOAD")) {
6373271d370SRui Ueyama       expect(")");
6383271d370SRui Ueyama       Cmd->Noload = true;
6393271d370SRui Ueyama       return;
6403271d370SRui Ueyama     }
6411c08e9f5SGeorge Rimar     if (consume("COPY") || consume("INFO") || consume("OVERLAY")) {
6421c08e9f5SGeorge Rimar       expect(")");
6431c08e9f5SGeorge Rimar       Cmd->NonAlloc = true;
6441c08e9f5SGeorge Rimar       return;
6451c08e9f5SGeorge Rimar     }
6463271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6473271d370SRui Ueyama     expect(")");
6483271d370SRui Ueyama   } else {
6493271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6503271d370SRui Ueyama   }
6513271d370SRui Ueyama 
652fbb0463fSGeorge Rimar   if (consume("(")) {
653fbb0463fSGeorge Rimar     expect("NOLOAD");
654fbb0463fSGeorge Rimar     expect(")");
655fbb0463fSGeorge Rimar     Cmd->Noload = true;
656fbb0463fSGeorge Rimar   }
657fbb0463fSGeorge Rimar }
658fbb0463fSGeorge Rimar 
659f22ec9ddSGeorge Rimar static Expr checkAlignment(Expr E, std::string &Loc) {
660f22ec9ddSGeorge Rimar   return [=] {
661f22ec9ddSGeorge Rimar     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
662f22ec9ddSGeorge Rimar     if (!isPowerOf2_64(Alignment)) {
663f22ec9ddSGeorge Rimar       error(Loc + ": alignment must be power of 2");
664f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
665f22ec9ddSGeorge Rimar     }
666f22ec9ddSGeorge Rimar     return Alignment;
667f22ec9ddSGeorge Rimar   };
668f22ec9ddSGeorge Rimar }
669f22ec9ddSGeorge Rimar 
6708c022ca7SRafael Espindola OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
6718c022ca7SRafael Espindola   OutputSection *Cmd =
6728c022ca7SRafael Espindola       Script->createOutputSection(OutSec, getCurrentLocation());
6733271d370SRui Ueyama 
6743271d370SRui Ueyama   if (peek() != ":")
6753271d370SRui Ueyama     readSectionAddressType(Cmd);
6762ec34544SRui Ueyama   expect(":");
6772ec34544SRui Ueyama 
678f22ec9ddSGeorge Rimar   std::string Location = getCurrentLocation();
6792ec34544SRui Ueyama   if (consume("AT"))
6802ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
6812ec34544SRui Ueyama   if (consume("ALIGN"))
682f22ec9ddSGeorge Rimar     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
6832ec34544SRui Ueyama   if (consume("SUBALIGN"))
684f22ec9ddSGeorge Rimar     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
6852ec34544SRui Ueyama 
6862ec34544SRui Ueyama   // Parse constraints.
6872ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
6882ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
6892ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
6902ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
6912ec34544SRui Ueyama   expect("{");
6922ec34544SRui Ueyama 
693b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
6942ec34544SRui Ueyama     StringRef Tok = next();
6952ec34544SRui Ueyama     if (Tok == ";") {
6962ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
697b579c439SRui Ueyama     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
6986b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Assign);
699f0403c60SRui Ueyama     } else if (ByteCommand *Data = readByteCommand(Tok)) {
7006b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Data);
7012ec34544SRui Ueyama     } else if (Tok == "ASSERT") {
7026b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readAssert());
7032ec34544SRui Ueyama       expect(";");
7042ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
7052ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
7062ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
7072ec34544SRui Ueyama       // For ELF, we should ignore.
7082ec34544SRui Ueyama     } else if (Tok == "FILL") {
7092ec34544SRui Ueyama       Cmd->Filler = readFill();
7102ec34544SRui Ueyama     } else if (Tok == "SORT") {
7112ec34544SRui Ueyama       readSort();
7122ec34544SRui Ueyama     } else if (peek() == "(") {
7136b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
7142ec34544SRui Ueyama     } else {
7152ec34544SRui Ueyama       setError("unknown command " + Tok);
7162ec34544SRui Ueyama     }
7172ec34544SRui Ueyama   }
7182ec34544SRui Ueyama 
7192ec34544SRui Ueyama   if (consume(">"))
7202ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
7212ec34544SRui Ueyama 
7225d01a8beSGeorge Rimar   if (consume("AT")) {
7235d01a8beSGeorge Rimar     expect(">");
7245d01a8beSGeorge Rimar     Cmd->LMARegionName = next();
7255d01a8beSGeorge Rimar   }
7265d01a8beSGeorge Rimar 
7275d01a8beSGeorge Rimar   if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
7285d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
7295d01a8beSGeorge Rimar 
7302ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
7312ec34544SRui Ueyama 
7322ec34544SRui Ueyama   if (consume("="))
7338acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
7342ec34544SRui Ueyama   else if (peek().startswith("="))
7358acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
7362ec34544SRui Ueyama 
7372ec34544SRui Ueyama   // Consume optional comma following output section command.
7382ec34544SRui Ueyama   consume(",");
7392ec34544SRui Ueyama 
7402ec34544SRui Ueyama   return Cmd;
7412ec34544SRui Ueyama }
7422ec34544SRui Ueyama 
7438acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
7448acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
7452ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
7462ec34544SRui Ueyama //
7478acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
7488acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
7498acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
7508acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
751b58079d4SRui Ueyama   uint32_t V = 0;
752ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
7532ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
754b58079d4SRui Ueyama 
755b58079d4SRui Ueyama   uint32_t Buf;
756b58079d4SRui Ueyama   write32be(&Buf, V);
757b58079d4SRui Ueyama   return Buf;
7582ec34544SRui Ueyama }
7592ec34544SRui Ueyama 
7602ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
7612ec34544SRui Ueyama   expect("(");
7622ec34544SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
7632ec34544SRui Ueyama   Cmd->Provide = Provide;
7642ec34544SRui Ueyama   Cmd->Hidden = Hidden;
7652ec34544SRui Ueyama   expect(")");
7662ec34544SRui Ueyama   expect(";");
7672ec34544SRui Ueyama   return Cmd;
7682ec34544SRui Ueyama }
7692ec34544SRui Ueyama 
7702ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
7712ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
7722ec34544SRui Ueyama   if (peek() == "=" || peek() == "+=") {
7732ec34544SRui Ueyama     Cmd = readAssignment(Tok);
7742ec34544SRui Ueyama     expect(";");
7752ec34544SRui Ueyama   } else if (Tok == "PROVIDE") {
7762ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
7772ec34544SRui Ueyama   } else if (Tok == "HIDDEN") {
7782ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
7792ec34544SRui Ueyama   } else if (Tok == "PROVIDE_HIDDEN") {
7802ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
7812ec34544SRui Ueyama   }
7822ec34544SRui Ueyama   return Cmd;
7832ec34544SRui Ueyama }
7842ec34544SRui Ueyama 
7852ec34544SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
7862ec34544SRui Ueyama   StringRef Op = next();
7872ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
7882ec34544SRui Ueyama   Expr E = readExpr();
7892ec34544SRui Ueyama   if (Op == "+=") {
7902ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
791722221f5SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
7922ec34544SRui Ueyama   }
7932ec34544SRui Ueyama   return make<SymbolAssignment>(Name, E, getCurrentLocation());
7942ec34544SRui Ueyama }
7952ec34544SRui Ueyama 
7962ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
7972ec34544SRui Ueyama // script expression.
7982ec34544SRui Ueyama Expr ScriptParser::readExpr() {
7992ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
8002ec34544SRui Ueyama   // they apply different tokenization rules.
8012ec34544SRui Ueyama   bool Orig = InExpr;
8022ec34544SRui Ueyama   InExpr = true;
8032ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
8042ec34544SRui Ueyama   InExpr = Orig;
8052ec34544SRui Ueyama   return E;
8062ec34544SRui Ueyama }
8072ec34544SRui Ueyama 
8082ec34544SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
8092ec34544SRui Ueyama   if (Op == "+")
8102ec34544SRui Ueyama     return [=] { return add(L(), R()); };
8112ec34544SRui Ueyama   if (Op == "-")
8122ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
813b579c439SRui Ueyama   if (Op == "*")
8141d20222aSRui Ueyama     return [=] { return L().getValue() * R().getValue(); };
815b579c439SRui Ueyama   if (Op == "/")
816b579c439SRui Ueyama     return [=] { return div(L(), R()); };
817*39ba31ffSRui Ueyama   if (Op == "%")
818*39ba31ffSRui Ueyama     return [=] { return mod(L(), R()); };
8192ec34544SRui Ueyama   if (Op == "<<")
8207e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
8212ec34544SRui Ueyama   if (Op == ">>")
8227e915511SRui Ueyama     return [=] { return L().getValue() >> R().getValue(); };
8232ec34544SRui Ueyama   if (Op == "<")
8242ec34544SRui Ueyama     return [=] { return L().getValue() < R().getValue(); };
8252ec34544SRui Ueyama   if (Op == ">")
8262ec34544SRui Ueyama     return [=] { return L().getValue() > R().getValue(); };
8272ec34544SRui Ueyama   if (Op == ">=")
8282ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
8292ec34544SRui Ueyama   if (Op == "<=")
8302ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
8312ec34544SRui Ueyama   if (Op == "==")
8322ec34544SRui Ueyama     return [=] { return L().getValue() == R().getValue(); };
8332ec34544SRui Ueyama   if (Op == "!=")
8342ec34544SRui Ueyama     return [=] { return L().getValue() != R().getValue(); };
8352ec34544SRui Ueyama   if (Op == "&")
8362ec34544SRui Ueyama     return [=] { return bitAnd(L(), R()); };
8372ec34544SRui Ueyama   if (Op == "|")
8382ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
8392ec34544SRui Ueyama   llvm_unreachable("invalid operator");
8402ec34544SRui Ueyama }
8412ec34544SRui Ueyama 
8422ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
8432ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
8442ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
845b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
8462ec34544SRui Ueyama     // Read an operator and an expression.
8472ec34544SRui Ueyama     if (consume("?"))
8482ec34544SRui Ueyama       return readTernary(Lhs);
8492ec34544SRui Ueyama     StringRef Op1 = peek();
8502ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
8512ec34544SRui Ueyama       break;
8522ec34544SRui Ueyama     skip();
8532ec34544SRui Ueyama     Expr Rhs = readPrimary();
8542ec34544SRui Ueyama 
8552ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
8562ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
8572ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
8582ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
8592ec34544SRui Ueyama     while (!atEOF()) {
8602ec34544SRui Ueyama       StringRef Op2 = peek();
8612ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
8622ec34544SRui Ueyama         break;
8632ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
8642ec34544SRui Ueyama     }
8652ec34544SRui Ueyama 
8662ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
8672ec34544SRui Ueyama   }
8682ec34544SRui Ueyama   return Lhs;
8692ec34544SRui Ueyama }
8702ec34544SRui Ueyama 
8715fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
8725fb17128SGeorge Rimar   std::string Location = getCurrentLocation();
8735fb17128SGeorge Rimar   return [=]() -> uint64_t {
8745fb17128SGeorge Rimar     if (Target)
8752ec34544SRui Ueyama       return Target->PageSize;
8765fb17128SGeorge Rimar     error(Location + ": unable to calculate page size");
8775fb17128SGeorge Rimar     return 4096; // Return a dummy value.
8785fb17128SGeorge Rimar   };
8795fb17128SGeorge Rimar }
8805fb17128SGeorge Rimar 
8815fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
8825fb17128SGeorge Rimar   StringRef S = readParenLiteral();
8835fb17128SGeorge Rimar   if (S == "COMMONPAGESIZE")
8845fb17128SGeorge Rimar     return getPageSize();
8852ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
8865fb17128SGeorge Rimar     return [] { return Config->MaxPageSize; };
8875fb17128SGeorge Rimar   setError("unknown constant: " + S);
8885fb17128SGeorge Rimar   return {};
8892ec34544SRui Ueyama }
8902ec34544SRui Ueyama 
8915c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
8925c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
8935c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
8945c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
8952ec34544SRui Ueyama   // Hexadecimal
8965c65088fSRui Ueyama   uint64_t Val;
8974092016bSRui Ueyama   if (Tok.startswith_lower("0x")) {
8984092016bSRui Ueyama     if (!to_integer(Tok.substr(2), Val, 16))
8994092016bSRui Ueyama       return None;
9005c65088fSRui Ueyama     return Val;
9014092016bSRui Ueyama   }
9024092016bSRui Ueyama   if (Tok.endswith_lower("H")) {
9034092016bSRui Ueyama     if (!to_integer(Tok.drop_back(), Val, 16))
9044092016bSRui Ueyama       return None;
9055c65088fSRui Ueyama     return Val;
9064092016bSRui Ueyama   }
9072ec34544SRui Ueyama 
9082ec34544SRui Ueyama   // Decimal
9092ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
910ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9115c65088fSRui Ueyama       return None;
9125c65088fSRui Ueyama     return Val * 1024;
9132ec34544SRui Ueyama   }
9145c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
915ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9165c65088fSRui Ueyama       return None;
9175c65088fSRui Ueyama     return Val * 1024 * 1024;
9185c65088fSRui Ueyama   }
919ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
9205c65088fSRui Ueyama     return None;
9215c65088fSRui Ueyama   return Val;
9222ec34544SRui Ueyama }
9232ec34544SRui Ueyama 
924f0403c60SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
925b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
9262ec34544SRui Ueyama                  .Case("BYTE", 1)
9272ec34544SRui Ueyama                  .Case("SHORT", 2)
9282ec34544SRui Ueyama                  .Case("LONG", 4)
9292ec34544SRui Ueyama                  .Case("QUAD", 8)
9302ec34544SRui Ueyama                  .Default(-1);
9312ec34544SRui Ueyama   if (Size == -1)
9322ec34544SRui Ueyama     return nullptr;
933f0403c60SRui Ueyama   return make<ByteCommand>(readParenExpr(), Size);
9342ec34544SRui Ueyama }
9352ec34544SRui Ueyama 
9362ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
9372ec34544SRui Ueyama   expect("(");
9385e9c7762SRafael Espindola   bool Orig = InExpr;
9395e9c7762SRafael Espindola   InExpr = false;
9402ec34544SRui Ueyama   StringRef Tok = next();
9415e9c7762SRafael Espindola   InExpr = Orig;
9422ec34544SRui Ueyama   expect(")");
9432ec34544SRui Ueyama   return Tok;
9442ec34544SRui Ueyama }
9452ec34544SRui Ueyama 
946617e2f98SRui Ueyama static void checkIfExists(OutputSection *Cmd, StringRef Location) {
94705c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
94805c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
94905c4f67cSRafael Espindola }
95005c4f67cSRafael Espindola 
9512ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
9522ec34544SRui Ueyama   if (peek() == "(")
9532ec34544SRui Ueyama     return readParenExpr();
9542ec34544SRui Ueyama 
9555c65088fSRui Ueyama   if (consume("~")) {
9562ec34544SRui Ueyama     Expr E = readPrimary();
957b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
9582ec34544SRui Ueyama   }
9596f1d954eSHafiz Abid Qadeer   if (consume("!")) {
9606f1d954eSHafiz Abid Qadeer     Expr E = readPrimary();
9616f1d954eSHafiz Abid Qadeer     return [=] { return !E().getValue(); };
9626f1d954eSHafiz Abid Qadeer   }
9635c65088fSRui Ueyama   if (consume("-")) {
9642ec34544SRui Ueyama     Expr E = readPrimary();
965b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
9662ec34544SRui Ueyama   }
9672ec34544SRui Ueyama 
9685c65088fSRui Ueyama   StringRef Tok = next();
9695c65088fSRui Ueyama   std::string Location = getCurrentLocation();
9705c65088fSRui Ueyama 
9712ec34544SRui Ueyama   // Built-in functions are parsed here.
9722ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
9732ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
9742ec34544SRui Ueyama     Expr Inner = readParenExpr();
9752ec34544SRui Ueyama     return [=] {
9762ec34544SRui Ueyama       ExprValue I = Inner();
9772ec34544SRui Ueyama       I.ForceAbsolute = true;
9782ec34544SRui Ueyama       return I;
9792ec34544SRui Ueyama     };
9802ec34544SRui Ueyama   }
9812ec34544SRui Ueyama   if (Tok == "ADDR") {
9822ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9834fbe3518SRui Ueyama     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
98441c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
9854fbe3518SRui Ueyama       checkIfExists(Sec, Location);
9864fbe3518SRui Ueyama       return {Sec, false, 0, Location};
98741c7ab4aSGeorge Rimar     };
9882ec34544SRui Ueyama   }
9892ec34544SRui Ueyama   if (Tok == "ALIGN") {
9902ec34544SRui Ueyama     expect("(");
9912ec34544SRui Ueyama     Expr E = readExpr();
992f22ec9ddSGeorge Rimar     if (consume(")")) {
993f22ec9ddSGeorge Rimar       E = checkAlignment(E, Location);
994f22ec9ddSGeorge Rimar       return [=] { return alignTo(Script->getDot(), E().getValue()); };
995f22ec9ddSGeorge Rimar     }
996b579c439SRui Ueyama     expect(",");
997f22ec9ddSGeorge Rimar     Expr E2 = checkAlignment(readExpr(), Location);
9982ec34544SRui Ueyama     expect(")");
9993c6de1a6SPetr Hosek     return [=] {
10003c6de1a6SPetr Hosek       ExprValue V = E();
1001f22ec9ddSGeorge Rimar       V.Alignment = E2().getValue();
10023c6de1a6SPetr Hosek       return V;
10033c6de1a6SPetr Hosek     };
10042ec34544SRui Ueyama   }
10052ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
10062ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10078c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1008617e2f98SRui Ueyama     return [=] {
1009617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1010617e2f98SRui Ueyama       return Cmd->Alignment;
1011617e2f98SRui Ueyama     };
10122ec34544SRui Ueyama   }
10132ec34544SRui Ueyama   if (Tok == "ASSERT")
101423af89ccSRui Ueyama     return readAssertExpr();
10155fb17128SGeorge Rimar   if (Tok == "CONSTANT")
10165fb17128SGeorge Rimar     return readConstant();
10172ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
10182ec34544SRui Ueyama     expect("(");
10192ec34544SRui Ueyama     Expr E = readExpr();
10202ec34544SRui Ueyama     expect(",");
10212ec34544SRui Ueyama     readExpr();
10222ec34544SRui Ueyama     expect(")");
102360833f6eSGeorge Rimar     return [=] {
102460833f6eSGeorge Rimar       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
102560833f6eSGeorge Rimar     };
10262ec34544SRui Ueyama   }
10272ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
10282ec34544SRui Ueyama     expect("(");
10292ec34544SRui Ueyama     expect(".");
10302ec34544SRui Ueyama     expect(")");
10312ec34544SRui Ueyama     return [] { return Script->getDot(); };
10322ec34544SRui Ueyama   }
10332ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
10342ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
10352ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
10362ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
10372ec34544SRui Ueyama     expect("(");
10382ec34544SRui Ueyama     readExpr();
10392ec34544SRui Ueyama     expect(",");
10402ec34544SRui Ueyama     readExpr();
10412ec34544SRui Ueyama     expect(")");
10425fb17128SGeorge Rimar     Expr E = getPageSize();
10435fb17128SGeorge Rimar     return [=] { return alignTo(Script->getDot(), E().getValue()); };
10442ec34544SRui Ueyama   }
10452ec34544SRui Ueyama   if (Tok == "DEFINED") {
10462ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10479b18f50fSRui Ueyama     return [=] { return Symtab->find(Name) ? 1 : 0; };
10482ec34544SRui Ueyama   }
104991b95b61SRui Ueyama   if (Tok == "LENGTH") {
105091b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1051ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name) == 0)
105291b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1053ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Length; };
105491b95b61SRui Ueyama   }
10552ec34544SRui Ueyama   if (Tok == "LOADADDR") {
10562ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10578c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1058617e2f98SRui Ueyama     return [=] {
1059617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1060617e2f98SRui Ueyama       return Cmd->getLMA();
1061617e2f98SRui Ueyama     };
10622ec34544SRui Ueyama   }
106391b95b61SRui Ueyama   if (Tok == "ORIGIN") {
106491b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1065ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name) == 0)
106691b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1067ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Origin; };
106891b95b61SRui Ueyama   }
10692ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
10702ec34544SRui Ueyama     expect("(");
10712ec34544SRui Ueyama     skip();
10722ec34544SRui Ueyama     expect(",");
10732ec34544SRui Ueyama     Expr E = readExpr();
10742ec34544SRui Ueyama     expect(")");
10752ec34544SRui Ueyama     return [=] { return E(); };
10762ec34544SRui Ueyama   }
10772ec34544SRui Ueyama   if (Tok == "SIZEOF") {
10782ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10798c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
108005c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
108105c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
108205c4f67cSRafael Espindola     // be empty.
10838c022ca7SRafael Espindola     return [=] { return Cmd->Size; };
10842ec34544SRui Ueyama   }
10852ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
10862ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
10872ec34544SRui Ueyama 
10884eb2eccbSRui Ueyama   // Tok is the dot.
10894eb2eccbSRui Ueyama   if (Tok == ".")
1090722221f5SRui Ueyama     return [=] { return Script->getSymbolValue(Tok, Location); };
10914eb2eccbSRui Ueyama 
10922ec34544SRui Ueyama   // Tok is a literal number.
10935c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
10945c65088fSRui Ueyama     return [=] { return *Val; };
10952ec34544SRui Ueyama 
10962ec34544SRui Ueyama   // Tok is a symbol name.
10972ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
10982ec34544SRui Ueyama     setError("malformed number: " + Tok);
1099ac27de9dSRui Ueyama   Script->ReferencedSymbols.push_back(Tok);
1100722221f5SRui Ueyama   return [=] { return Script->getSymbolValue(Tok, Location); };
11012ec34544SRui Ueyama }
11022ec34544SRui Ueyama 
11032ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
11042ec34544SRui Ueyama   Expr L = readExpr();
11052ec34544SRui Ueyama   expect(":");
11062ec34544SRui Ueyama   Expr R = readExpr();
11072ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
11082ec34544SRui Ueyama }
11092ec34544SRui Ueyama 
11102ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
11112ec34544SRui Ueyama   expect("(");
11122ec34544SRui Ueyama   Expr E = readExpr();
11132ec34544SRui Ueyama   expect(")");
11142ec34544SRui Ueyama   return E;
11152ec34544SRui Ueyama }
11162ec34544SRui Ueyama 
11172ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
11182ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
1119b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
11202ec34544SRui Ueyama     StringRef Tok = next();
11212ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
11222ec34544SRui Ueyama   }
11232ec34544SRui Ueyama   return Phdrs;
11242ec34544SRui Ueyama }
11252ec34544SRui Ueyama 
11262ec34544SRui Ueyama // Read a program header type name. The next token must be a
11272ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
11282ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
11292ec34544SRui Ueyama   StringRef Tok = next();
11305c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11315c65088fSRui Ueyama     return *Val;
11322ec34544SRui Ueyama 
11332ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
11342ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
11352ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
11362ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
11372ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
11382ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
11392ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
11402ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
11412ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
11422ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
11432ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
11442ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
11452ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
11462ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
11472ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
11482ec34544SRui Ueyama                      .Default(-1);
11492ec34544SRui Ueyama 
11502ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
11512ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
11522ec34544SRui Ueyama     return PT_NULL;
11532ec34544SRui Ueyama   }
11542ec34544SRui Ueyama   return Ret;
11552ec34544SRui Ueyama }
11562ec34544SRui Ueyama 
11572ec34544SRui Ueyama // Reads an anonymous version declaration.
11582ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
11592ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11602ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11612ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11622ec34544SRui Ueyama 
11632ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11642ec34544SRui Ueyama     if (V.Name == "*")
11652ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11662ec34544SRui Ueyama     else
11672ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11682ec34544SRui Ueyama   }
11692ec34544SRui Ueyama 
11702ec34544SRui Ueyama   for (SymbolVersion V : Globals)
11712ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
11722ec34544SRui Ueyama 
11732ec34544SRui Ueyama   expect(";");
11742ec34544SRui Ueyama }
11752ec34544SRui Ueyama 
11762ec34544SRui Ueyama // Reads a non-anonymous version definition,
11772ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
11782ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
11792ec34544SRui Ueyama   // Read a symbol list.
11802ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11812ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11822ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11832ec34544SRui Ueyama 
11842ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11852ec34544SRui Ueyama     if (V.Name == "*")
11862ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11872ec34544SRui Ueyama     else
11882ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11892ec34544SRui Ueyama   }
11902ec34544SRui Ueyama 
11912ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
11922ec34544SRui Ueyama   VersionDefinition Ver;
11932ec34544SRui Ueyama   Ver.Name = VerStr;
11942ec34544SRui Ueyama   Ver.Globals = Globals;
11952ec34544SRui Ueyama 
11962ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
11972ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
11982ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
11992ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
12002ec34544SRui Ueyama 
12012ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
12022ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
12032ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
12042ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
12052ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
12062ec34544SRui Ueyama   if (peek() != ";")
12072ec34544SRui Ueyama     skip();
12082ec34544SRui Ueyama   expect(";");
12092ec34544SRui Ueyama }
12102ec34544SRui Ueyama 
12111e77ad14SRui Ueyama static bool hasWildcard(StringRef S) {
12121e77ad14SRui Ueyama   return S.find_first_of("?*[") != StringRef::npos;
12131e77ad14SRui Ueyama }
12141e77ad14SRui Ueyama 
12152ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
12162ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
12172ec34544SRui Ueyama ScriptParser::readSymbols() {
12182ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12192ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12202ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
12212ec34544SRui Ueyama 
1222b8a59c8aSBob Haarman   while (!errorCount()) {
12232ec34544SRui Ueyama     if (consume("}"))
12242ec34544SRui Ueyama       break;
12252ec34544SRui Ueyama     if (consumeLabel("local")) {
12262ec34544SRui Ueyama       V = &Locals;
12272ec34544SRui Ueyama       continue;
12282ec34544SRui Ueyama     }
12292ec34544SRui Ueyama     if (consumeLabel("global")) {
12302ec34544SRui Ueyama       V = &Globals;
12312ec34544SRui Ueyama       continue;
12322ec34544SRui Ueyama     }
12332ec34544SRui Ueyama 
12342ec34544SRui Ueyama     if (consume("extern")) {
12352ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
12362ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
12372ec34544SRui Ueyama     } else {
12382ec34544SRui Ueyama       StringRef Tok = next();
12392ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
12402ec34544SRui Ueyama     }
12412ec34544SRui Ueyama     expect(";");
12422ec34544SRui Ueyama   }
12432ec34544SRui Ueyama   return {Locals, Globals};
12442ec34544SRui Ueyama }
12452ec34544SRui Ueyama 
12462ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
12472ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
124817324d8bSRui Ueyama //
124917324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
125017324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
12512ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
12522ec34544SRui Ueyama   StringRef Tok = next();
12532ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
12542ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
12552ec34544SRui Ueyama     setError("Unknown language");
12562ec34544SRui Ueyama   expect("{");
12572ec34544SRui Ueyama 
12582ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
1259b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
12602ec34544SRui Ueyama     StringRef Tok = next();
12612ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
12622ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
126317324d8bSRui Ueyama     if (consume("}"))
126417324d8bSRui Ueyama       return Ret;
12652ec34544SRui Ueyama     expect(";");
12662ec34544SRui Ueyama   }
12672ec34544SRui Ueyama 
12682ec34544SRui Ueyama   expect("}");
12692ec34544SRui Ueyama   return Ret;
12702ec34544SRui Ueyama }
12712ec34544SRui Ueyama 
12722ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
12732ec34544SRui Ueyama                                             StringRef S3) {
1274b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
12752ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
12762ec34544SRui Ueyama     return 0;
12772ec34544SRui Ueyama   }
12782ec34544SRui Ueyama   expect("=");
1279040af7deSRui Ueyama   return readExpr()().getValue();
12802ec34544SRui Ueyama }
12812ec34544SRui Ueyama 
12822ec34544SRui Ueyama // Parse the MEMORY command as specified in:
12832ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
12842ec34544SRui Ueyama //
12852ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
12862ec34544SRui Ueyama void ScriptParser::readMemory() {
12872ec34544SRui Ueyama   expect("{");
1288b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
12892ec34544SRui Ueyama     StringRef Name = next();
12902ec34544SRui Ueyama 
12912ec34544SRui Ueyama     uint32_t Flags = 0;
12922ec34544SRui Ueyama     uint32_t NegFlags = 0;
12932ec34544SRui Ueyama     if (consume("(")) {
12942ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
12952ec34544SRui Ueyama       expect(")");
12962ec34544SRui Ueyama     }
12972ec34544SRui Ueyama     expect(":");
12982ec34544SRui Ueyama 
12992ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
13002ec34544SRui Ueyama     expect(",");
13012ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
13022ec34544SRui Ueyama 
13035f37541cSGeorge Rimar     // Add the memory region to the region map.
1304ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name))
13052ec34544SRui Ueyama       setError("region '" + Name + "' already defined");
1306490f0a4dSRafael Espindola     MemoryRegion *MR =
1307490f0a4dSRafael Espindola         make<MemoryRegion>(Name, Origin, Length, Flags, NegFlags);
1308ac27de9dSRui Ueyama     Script->MemoryRegions[Name] = MR;
13092ec34544SRui Ueyama   }
13102ec34544SRui Ueyama }
13112ec34544SRui Ueyama 
13122ec34544SRui Ueyama // This function parses the attributes used to match against section
13132ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
13142ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
13152ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
13162ec34544SRui Ueyama   uint32_t Flags = 0;
13172ec34544SRui Ueyama   uint32_t NegFlags = 0;
13182ec34544SRui Ueyama   bool Invert = false;
13192ec34544SRui Ueyama 
13202ec34544SRui Ueyama   for (char C : next().lower()) {
13212ec34544SRui Ueyama     uint32_t Flag = 0;
13222ec34544SRui Ueyama     if (C == '!')
13232ec34544SRui Ueyama       Invert = !Invert;
13242ec34544SRui Ueyama     else if (C == 'w')
13252ec34544SRui Ueyama       Flag = SHF_WRITE;
13262ec34544SRui Ueyama     else if (C == 'x')
13272ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
13282ec34544SRui Ueyama     else if (C == 'a')
13292ec34544SRui Ueyama       Flag = SHF_ALLOC;
13302ec34544SRui Ueyama     else if (C != 'r')
13312ec34544SRui Ueyama       setError("invalid memory region attribute");
13322ec34544SRui Ueyama 
13332ec34544SRui Ueyama     if (Invert)
13342ec34544SRui Ueyama       NegFlags |= Flag;
13352ec34544SRui Ueyama     else
13362ec34544SRui Ueyama       Flags |= Flag;
13372ec34544SRui Ueyama   }
13382ec34544SRui Ueyama   return {Flags, NegFlags};
13392ec34544SRui Ueyama }
13402ec34544SRui Ueyama 
13412ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
13422ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
13432ec34544SRui Ueyama }
13442ec34544SRui Ueyama 
13452ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
13462ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
13472ec34544SRui Ueyama }
13482ec34544SRui Ueyama 
13492ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
13502ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
13512ec34544SRui Ueyama }
13528c7e8cceSPetr Hosek 
13538c7e8cceSPetr Hosek void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
13548c7e8cceSPetr Hosek   ScriptParser(MB).readDefsym(Name);
13558c7e8cceSPetr Hosek }
1356