12ec34544SRui Ueyama //===- ScriptParser.cpp ---------------------------------------------------===//
22ec34544SRui Ueyama //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62ec34544SRui Ueyama //
72ec34544SRui Ueyama //===----------------------------------------------------------------------===//
805f6b852SRui Ueyama //
905f6b852SRui Ueyama // This file contains a recursive-descendent parser for linker scripts.
1005f6b852SRui Ueyama // Parsed results are stored to Config and Script global objects.
1105f6b852SRui Ueyama //
1205f6b852SRui Ueyama //===----------------------------------------------------------------------===//
132ec34544SRui Ueyama 
142ec34544SRui Ueyama #include "ScriptParser.h"
152ec34544SRui Ueyama #include "Config.h"
162ec34544SRui Ueyama #include "Driver.h"
172ec34544SRui Ueyama #include "InputSection.h"
182ec34544SRui Ueyama #include "LinkerScript.h"
192ec34544SRui Ueyama #include "OutputSections.h"
202ec34544SRui Ueyama #include "ScriptLexer.h"
212ec34544SRui Ueyama #include "Symbols.h"
222ec34544SRui Ueyama #include "Target.h"
232017d52bSRui Ueyama #include "lld/Common/Memory.h"
242ec34544SRui Ueyama #include "llvm/ADT/SmallString.h"
252ec34544SRui Ueyama #include "llvm/ADT/StringRef.h"
260440be4aSRui Ueyama #include "llvm/ADT/StringSet.h"
272ec34544SRui Ueyama #include "llvm/ADT/StringSwitch.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
292ec34544SRui Ueyama #include "llvm/Support/Casting.h"
302ec34544SRui Ueyama #include "llvm/Support/ErrorHandling.h"
312ec34544SRui Ueyama #include "llvm/Support/FileSystem.h"
322ec34544SRui Ueyama #include "llvm/Support/Path.h"
33dbd0ad33SPeter Smith #include "llvm/Support/ScopedPrinter.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 
42bd8cfe65SFangrui Song namespace lld {
43bd8cfe65SFangrui Song namespace elf {
4496b3fe02SRui Ueyama namespace {
4596b3fe02SRui Ueyama class ScriptParser final : ScriptLexer {
462ec34544SRui Ueyama public:
473837f427SRui Ueyama   ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) {
4811ae59f0SRui Ueyama     // Initialize IsUnderSysroot
493837f427SRui Ueyama     if (config->sysroot == "")
5011ae59f0SRui Ueyama       return;
513837f427SRui Ueyama     StringRef path = mb.getBufferIdentifier();
523837f427SRui Ueyama     for (; !path.empty(); path = sys::path::parent_path(path)) {
533837f427SRui Ueyama       if (!sys::fs::equivalent(config->sysroot, path))
5411ae59f0SRui Ueyama         continue;
553837f427SRui Ueyama       isUnderSysroot = true;
5611ae59f0SRui Ueyama       return;
5711ae59f0SRui Ueyama     }
5811ae59f0SRui Ueyama   }
592ec34544SRui Ueyama 
602ec34544SRui Ueyama   void readLinkerScript();
612ec34544SRui Ueyama   void readVersionScript();
622ec34544SRui Ueyama   void readDynamicList();
633837f427SRui Ueyama   void readDefsym(StringRef name);
642ec34544SRui Ueyama 
652ec34544SRui Ueyama private:
663837f427SRui Ueyama   void addFile(StringRef path);
672ec34544SRui Ueyama 
682ec34544SRui Ueyama   void readAsNeeded();
692ec34544SRui Ueyama   void readEntry();
702ec34544SRui Ueyama   void readExtern();
712ec34544SRui Ueyama   void readGroup();
722ec34544SRui Ueyama   void readInclude();
731d92aa73SRui Ueyama   void readInput();
742ec34544SRui Ueyama   void readMemory();
752ec34544SRui Ueyama   void readOutput();
762ec34544SRui Ueyama   void readOutputArch();
772ec34544SRui Ueyama   void readOutputFormat();
782ec34544SRui Ueyama   void readPhdrs();
795f37541cSGeorge Rimar   void readRegionAlias();
802ec34544SRui Ueyama   void readSearchDir();
812ec34544SRui Ueyama   void readSections();
82e262bb1aSRui Ueyama   void readTarget();
832ec34544SRui Ueyama   void readVersion();
842ec34544SRui Ueyama   void readVersionScriptCommand();
852ec34544SRui Ueyama 
863837f427SRui Ueyama   SymbolAssignment *readSymbolAssignment(StringRef name);
873837f427SRui Ueyama   ByteCommand *readByteCommand(StringRef tok);
88b0486051SSimon Atanasyan   std::array<uint8_t, 4> readFill();
893837f427SRui Ueyama   bool readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2);
903837f427SRui Ueyama   void readSectionAddressType(OutputSection *cmd);
91a582419aSGeorge Rimar   OutputSection *readOverlaySectionDescription();
923837f427SRui Ueyama   OutputSection *readOutputSectionDescription(StringRef outSec);
93a582419aSGeorge Rimar   std::vector<BaseCommand *> readOverlay();
942ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
95dbd0ad33SPeter Smith   std::pair<uint64_t, uint64_t> readInputSectionFlags();
963837f427SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef tok);
972ec34544SRui Ueyama   StringMatcher readFilePatterns();
982ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
99dbd0ad33SPeter Smith   InputSectionDescription *readInputSectionRules(StringRef filePattern,
100dbd0ad33SPeter Smith                                                  uint64_t withFlags,
101dbd0ad33SPeter Smith                                                  uint64_t withoutFlags);
1022ec34544SRui Ueyama   unsigned readPhdrType();
1032ec34544SRui Ueyama   SortSectionPolicy readSortKind();
1043837f427SRui Ueyama   SymbolAssignment *readProvideHidden(bool provide, bool hidden);
1053837f427SRui Ueyama   SymbolAssignment *readAssignment(StringRef tok);
1062ec34544SRui Ueyama   void readSort();
107d30a78b3SGeorge Rimar   Expr readAssert();
1085fb17128SGeorge Rimar   Expr readConstant();
1095fb17128SGeorge Rimar   Expr getPageSize();
1102ec34544SRui Ueyama 
11192b5b980SFangrui Song   Expr readMemoryAssignment(StringRef, StringRef, StringRef);
1122ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1132ec34544SRui Ueyama 
1143837f427SRui Ueyama   Expr combine(StringRef op, Expr l, Expr r);
1152ec34544SRui Ueyama   Expr readExpr();
1163837f427SRui Ueyama   Expr readExpr1(Expr lhs, int minPrec);
1172ec34544SRui Ueyama   StringRef readParenLiteral();
1182ec34544SRui Ueyama   Expr readPrimary();
1193837f427SRui Ueyama   Expr readTernary(Expr cond);
1202ec34544SRui Ueyama   Expr readParenExpr();
1212ec34544SRui Ueyama 
1222ec34544SRui Ueyama   // For parsing version script.
1232ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1242ec34544SRui Ueyama   void readAnonymousDeclaration();
1253837f427SRui Ueyama   void readVersionDeclaration(StringRef verStr);
1262ec34544SRui Ueyama 
1272ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1282ec34544SRui Ueyama   readSymbols();
1292ec34544SRui Ueyama 
130fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1313837f427SRui Ueyama   bool isUnderSysroot = false;
1320440be4aSRui Ueyama 
1330440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1343837f427SRui Ueyama   StringSet<> seen;
1352ec34544SRui Ueyama };
13696b3fe02SRui Ueyama } // namespace
1372ec34544SRui Ueyama 
1383837f427SRui Ueyama static StringRef unquote(StringRef s) {
1393837f427SRui Ueyama   if (s.startswith("\""))
1403837f427SRui Ueyama     return s.substr(1, s.size() - 2);
1413837f427SRui Ueyama   return s;
1421e77ad14SRui Ueyama }
1431e77ad14SRui Ueyama 
1442ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1452ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1463837f427SRui Ueyama static void moveAbsRight(ExprValue &a, ExprValue &b) {
1473837f427SRui Ueyama   if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
1483837f427SRui Ueyama     std::swap(a, b);
1493837f427SRui Ueyama   if (!b.isAbsolute())
1503837f427SRui Ueyama     error(a.loc + ": at least one side of the expression must be absolute");
1512ec34544SRui Ueyama }
1522ec34544SRui Ueyama 
1533837f427SRui Ueyama static ExprValue add(ExprValue a, ExprValue b) {
1543837f427SRui Ueyama   moveAbsRight(a, b);
1553837f427SRui Ueyama   return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
1562ec34544SRui Ueyama }
1572ec34544SRui Ueyama 
1583837f427SRui Ueyama static ExprValue sub(ExprValue a, ExprValue b) {
15963a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1603837f427SRui Ueyama   if (!a.isAbsolute() && !b.isAbsolute())
1613837f427SRui Ueyama     return a.getValue() - b.getValue();
1623837f427SRui Ueyama   return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
1632ec34544SRui Ueyama }
1642ec34544SRui Ueyama 
1653837f427SRui Ueyama static ExprValue bitAnd(ExprValue a, ExprValue b) {
1663837f427SRui Ueyama   moveAbsRight(a, b);
1673837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1683837f427SRui Ueyama           (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
1692ec34544SRui Ueyama }
1702ec34544SRui Ueyama 
1713837f427SRui Ueyama static ExprValue bitOr(ExprValue a, ExprValue b) {
1723837f427SRui Ueyama   moveAbsRight(a, b);
1733837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1743837f427SRui Ueyama           (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
1752ec34544SRui Ueyama }
1762ec34544SRui Ueyama 
1772ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1783837f427SRui Ueyama   config->hasDynamicList = true;
1792ec34544SRui Ueyama   expect("{");
1803837f427SRui Ueyama   std::vector<SymbolVersion> locals;
1813837f427SRui Ueyama   std::vector<SymbolVersion> globals;
1823837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
183d72d97b3SRafael Espindola   expect(";");
184d72d97b3SRafael Espindola 
185d72d97b3SRafael Espindola   if (!atEOF()) {
1862ec34544SRui Ueyama     setError("EOF expected, but got " + next());
187d72d97b3SRafael Espindola     return;
188d72d97b3SRafael Espindola   }
1893837f427SRui Ueyama   if (!locals.empty()) {
190d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
191d72d97b3SRafael Espindola     return;
192d72d97b3SRafael Espindola   }
193d72d97b3SRafael Espindola 
1943837f427SRui Ueyama   for (SymbolVersion v : globals)
1953837f427SRui Ueyama     config->dynamicList.push_back(v);
1962ec34544SRui Ueyama }
1972ec34544SRui Ueyama 
1982ec34544SRui Ueyama void ScriptParser::readVersionScript() {
1992ec34544SRui Ueyama   readVersionScriptCommand();
2002ec34544SRui Ueyama   if (!atEOF())
2012ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2022ec34544SRui Ueyama }
2032ec34544SRui Ueyama 
2042ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2052ec34544SRui Ueyama   if (consume("{")) {
2062ec34544SRui Ueyama     readAnonymousDeclaration();
2072ec34544SRui Ueyama     return;
2082ec34544SRui Ueyama   }
2092ec34544SRui Ueyama 
210b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2113837f427SRui Ueyama     StringRef verStr = next();
2123837f427SRui Ueyama     if (verStr == "{") {
2132ec34544SRui Ueyama       setError("anonymous version definition is used in "
2142ec34544SRui Ueyama                "combination with other version definitions");
2152ec34544SRui Ueyama       return;
2162ec34544SRui Ueyama     }
2172ec34544SRui Ueyama     expect("{");
2183837f427SRui Ueyama     readVersionDeclaration(verStr);
2192ec34544SRui Ueyama   }
2202ec34544SRui Ueyama }
2212ec34544SRui Ueyama 
2222ec34544SRui Ueyama void ScriptParser::readVersion() {
2232ec34544SRui Ueyama   expect("{");
2242ec34544SRui Ueyama   readVersionScriptCommand();
2252ec34544SRui Ueyama   expect("}");
2262ec34544SRui Ueyama }
2272ec34544SRui Ueyama 
2282ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2292ec34544SRui Ueyama   while (!atEOF()) {
2303837f427SRui Ueyama     StringRef tok = next();
2313837f427SRui Ueyama     if (tok == ";")
2322ec34544SRui Ueyama       continue;
2332ec34544SRui Ueyama 
2343837f427SRui Ueyama     if (tok == "ENTRY") {
2352ec34544SRui Ueyama       readEntry();
2363837f427SRui Ueyama     } else if (tok == "EXTERN") {
2372ec34544SRui Ueyama       readExtern();
2383837f427SRui Ueyama     } else if (tok == "GROUP") {
2392ec34544SRui Ueyama       readGroup();
2403837f427SRui Ueyama     } else if (tok == "INCLUDE") {
2412ec34544SRui Ueyama       readInclude();
2423837f427SRui Ueyama     } else if (tok == "INPUT") {
2431d92aa73SRui Ueyama       readInput();
2443837f427SRui Ueyama     } else if (tok == "MEMORY") {
2452ec34544SRui Ueyama       readMemory();
2463837f427SRui Ueyama     } else if (tok == "OUTPUT") {
2472ec34544SRui Ueyama       readOutput();
2483837f427SRui Ueyama     } else if (tok == "OUTPUT_ARCH") {
2492ec34544SRui Ueyama       readOutputArch();
2503837f427SRui Ueyama     } else if (tok == "OUTPUT_FORMAT") {
2512ec34544SRui Ueyama       readOutputFormat();
2523837f427SRui Ueyama     } else if (tok == "PHDRS") {
2532ec34544SRui Ueyama       readPhdrs();
2543837f427SRui Ueyama     } else if (tok == "REGION_ALIAS") {
2555f37541cSGeorge Rimar       readRegionAlias();
2563837f427SRui Ueyama     } else if (tok == "SEARCH_DIR") {
2572ec34544SRui Ueyama       readSearchDir();
2583837f427SRui Ueyama     } else if (tok == "SECTIONS") {
2592ec34544SRui Ueyama       readSections();
2603837f427SRui Ueyama     } else if (tok == "TARGET") {
261e262bb1aSRui Ueyama       readTarget();
2623837f427SRui Ueyama     } else if (tok == "VERSION") {
2632ec34544SRui Ueyama       readVersion();
2643837f427SRui Ueyama     } else if (SymbolAssignment *cmd = readAssignment(tok)) {
2653837f427SRui Ueyama       script->sectionCommands.push_back(cmd);
2662ec34544SRui Ueyama     } else {
2673837f427SRui Ueyama       setError("unknown directive: " + tok);
2682ec34544SRui Ueyama     }
2692ec34544SRui Ueyama   }
2702ec34544SRui Ueyama }
2712ec34544SRui Ueyama 
2723837f427SRui Ueyama void ScriptParser::readDefsym(StringRef name) {
273c1522816SGeorge Rimar   if (errorCount())
274c1522816SGeorge Rimar     return;
2753837f427SRui Ueyama   Expr e = readExpr();
2768c7e8cceSPetr Hosek   if (!atEOF())
2778c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
2783837f427SRui Ueyama   SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation());
2793837f427SRui Ueyama   script->sectionCommands.push_back(cmd);
2808c7e8cceSPetr Hosek }
2818c7e8cceSPetr Hosek 
2823837f427SRui Ueyama void ScriptParser::addFile(StringRef s) {
2833837f427SRui Ueyama   if (isUnderSysroot && s.startswith("/")) {
2843837f427SRui Ueyama     SmallString<128> pathData;
2853837f427SRui Ueyama     StringRef path = (config->sysroot + s).toStringRef(pathData);
2863837f427SRui Ueyama     if (sys::fs::exists(path)) {
28749a3ad21SRui Ueyama       driver->addFile(saver.save(path), /*withLOption=*/false);
2882ec34544SRui Ueyama       return;
2892ec34544SRui Ueyama     }
2902ec34544SRui Ueyama   }
2912ec34544SRui Ueyama 
2923837f427SRui Ueyama   if (s.startswith("/")) {
29349a3ad21SRui Ueyama     driver->addFile(s, /*withLOption=*/false);
2943837f427SRui Ueyama   } else if (s.startswith("=")) {
2953837f427SRui Ueyama     if (config->sysroot.empty())
29649a3ad21SRui Ueyama       driver->addFile(s.substr(1), /*withLOption=*/false);
2972ec34544SRui Ueyama     else
298136d27abSRui Ueyama       driver->addFile(saver.save(config->sysroot + "/" + s.substr(1)),
29949a3ad21SRui Ueyama                       /*withLOption=*/false);
3003837f427SRui Ueyama   } else if (s.startswith("-l")) {
3013837f427SRui Ueyama     driver->addLibrary(s.substr(2));
3023837f427SRui Ueyama   } else if (sys::fs::exists(s)) {
30349a3ad21SRui Ueyama     driver->addFile(s, /*withLOption=*/false);
3042ec34544SRui Ueyama   } else {
3053837f427SRui Ueyama     if (Optional<std::string> path = findFromSearchPaths(s))
30649a3ad21SRui Ueyama       driver->addFile(saver.save(*path), /*withLOption=*/true);
3072ec34544SRui Ueyama     else
3083837f427SRui Ueyama       setError("unable to find " + s);
3092ec34544SRui Ueyama   }
3102ec34544SRui Ueyama }
3112ec34544SRui Ueyama 
3122ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3132ec34544SRui Ueyama   expect("(");
3143837f427SRui Ueyama   bool orig = config->asNeeded;
3153837f427SRui Ueyama   config->asNeeded = true;
316b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3172ec34544SRui Ueyama     addFile(unquote(next()));
3183837f427SRui Ueyama   config->asNeeded = orig;
3192ec34544SRui Ueyama }
3202ec34544SRui Ueyama 
3212ec34544SRui Ueyama void ScriptParser::readEntry() {
3222ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3232ec34544SRui Ueyama   expect("(");
3243837f427SRui Ueyama   StringRef tok = next();
3253837f427SRui Ueyama   if (config->entry.empty())
3263837f427SRui Ueyama     config->entry = tok;
3272ec34544SRui Ueyama   expect(")");
3282ec34544SRui Ueyama }
3292ec34544SRui Ueyama 
3302ec34544SRui Ueyama void ScriptParser::readExtern() {
3312ec34544SRui Ueyama   expect("(");
332b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3333837f427SRui Ueyama     config->undefined.push_back(unquote(next()));
3342ec34544SRui Ueyama }
3352ec34544SRui Ueyama 
3362ec34544SRui Ueyama void ScriptParser::readGroup() {
3373837f427SRui Ueyama   bool orig = InputFile::isInGroup;
3383837f427SRui Ueyama   InputFile::isInGroup = true;
3391d92aa73SRui Ueyama   readInput();
3403837f427SRui Ueyama   InputFile::isInGroup = orig;
3413837f427SRui Ueyama   if (!orig)
3423837f427SRui Ueyama     ++InputFile::nextGroupId;
3432ec34544SRui Ueyama }
3442ec34544SRui Ueyama 
3452ec34544SRui Ueyama void ScriptParser::readInclude() {
3463837f427SRui Ueyama   StringRef tok = unquote(next());
3472ec34544SRui Ueyama 
3483837f427SRui Ueyama   if (!seen.insert(tok).second) {
3490440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3500440be4aSRui Ueyama     return;
3510440be4aSRui Ueyama   }
3520440be4aSRui Ueyama 
3533837f427SRui Ueyama   if (Optional<std::string> path = searchScript(tok)) {
3543837f427SRui Ueyama     if (Optional<MemoryBufferRef> mb = readFile(*path))
3553837f427SRui Ueyama       tokenize(*mb);
3562ec34544SRui Ueyama     return;
3572ec34544SRui Ueyama   }
3583837f427SRui Ueyama   setError("cannot find linker script " + tok);
3592ec34544SRui Ueyama }
3602ec34544SRui Ueyama 
3611d92aa73SRui Ueyama void ScriptParser::readInput() {
3621d92aa73SRui Ueyama   expect("(");
3631d92aa73SRui Ueyama   while (!errorCount() && !consume(")")) {
3641d92aa73SRui Ueyama     if (consume("AS_NEEDED"))
3651d92aa73SRui Ueyama       readAsNeeded();
3661d92aa73SRui Ueyama     else
3671d92aa73SRui Ueyama       addFile(unquote(next()));
3681d92aa73SRui Ueyama   }
3691d92aa73SRui Ueyama }
3701d92aa73SRui Ueyama 
3712ec34544SRui Ueyama void ScriptParser::readOutput() {
3722ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3732ec34544SRui Ueyama   expect("(");
3743837f427SRui Ueyama   StringRef tok = next();
3753837f427SRui Ueyama   if (config->outputFile.empty())
3763837f427SRui Ueyama     config->outputFile = unquote(tok);
3772ec34544SRui Ueyama   expect(")");
3782ec34544SRui Ueyama }
3792ec34544SRui Ueyama 
3802ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3812ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3822ec34544SRui Ueyama   expect("(");
383b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3842ec34544SRui Ueyama     skip();
3852ec34544SRui Ueyama }
3862ec34544SRui Ueyama 
3873837f427SRui Ueyama static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
3883837f427SRui Ueyama   return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
3894f8c8228SRui Ueyama       .Case("elf32-i386", {ELF32LEKind, EM_386})
3904f8c8228SRui Ueyama       .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
3914f8c8228SRui Ueyama       .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
3924f8c8228SRui Ueyama       .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
39319b134ccSDimitry Andric       .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
3944f8c8228SRui Ueyama       .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
3954134143cSRui Ueyama       .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
3964f8c8228SRui Ueyama       .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
3974f8c8228SRui Ueyama       .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
3984f8c8228SRui Ueyama       .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
3994134143cSRui Ueyama       .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
4004f8c8228SRui Ueyama       .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
4014f8c8228SRui Ueyama       .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
4024f8c8228SRui Ueyama       .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
4034f8c8228SRui Ueyama       .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
4044f8c8228SRui Ueyama       .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
40544d908d7SFangrui Song       .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})
40644d908d7SFangrui Song       .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})
4074f8c8228SRui Ueyama       .Default({ELFNoneKind, EM_NONE});
408ea8cd00aSRui Ueyama }
409ea8cd00aSRui Ueyama 
410ea8cd00aSRui Ueyama // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(bfdname, big, little).
411ea8cd00aSRui Ueyama // Currently we ignore big and little parameters.
4122ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
4132ec34544SRui Ueyama   expect("(");
414ea8cd00aSRui Ueyama 
4152822852fSShoaib Meenai   config->bfdname = unquote(next());
4162822852fSShoaib Meenai   StringRef s = config->bfdname;
4173837f427SRui Ueyama   if (s.consume_back("-freebsd"))
4183837f427SRui Ueyama     config->osabi = ELFOSABI_FREEBSD;
4194f8c8228SRui Ueyama 
4203837f427SRui Ueyama   std::tie(config->ekind, config->emachine) = parseBfdName(s);
4213837f427SRui Ueyama   if (config->emachine == EM_NONE)
4222822852fSShoaib Meenai     setError("unknown output format name: " + config->bfdname);
4233837f427SRui Ueyama   if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
4243837f427SRui Ueyama     config->mipsN32Abi = true;
425ea8cd00aSRui Ueyama 
426b579c439SRui Ueyama   if (consume(")"))
4272ec34544SRui Ueyama     return;
428b579c439SRui Ueyama   expect(",");
4292ec34544SRui Ueyama   skip();
4302ec34544SRui Ueyama   expect(",");
4312ec34544SRui Ueyama   skip();
4322ec34544SRui Ueyama   expect(")");
4332ec34544SRui Ueyama }
4342ec34544SRui Ueyama 
4352ec34544SRui Ueyama void ScriptParser::readPhdrs() {
4362ec34544SRui Ueyama   expect("{");
4372ec34544SRui Ueyama 
438b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4393837f427SRui Ueyama     PhdrsCommand cmd;
4403837f427SRui Ueyama     cmd.name = next();
4413837f427SRui Ueyama     cmd.type = readPhdrType();
442b579c439SRui Ueyama 
443b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
444b579c439SRui Ueyama       if (consume("FILEHDR"))
4453837f427SRui Ueyama         cmd.hasFilehdr = true;
446b579c439SRui Ueyama       else if (consume("PHDRS"))
4473837f427SRui Ueyama         cmd.hasPhdrs = true;
448b579c439SRui Ueyama       else if (consume("AT"))
4493837f427SRui Ueyama         cmd.lmaExpr = readParenExpr();
450b579c439SRui Ueyama       else if (consume("FLAGS"))
4513837f427SRui Ueyama         cmd.flags = readParenExpr()().getValue();
452b579c439SRui Ueyama       else
453b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
454b579c439SRui Ueyama     }
4550ae2c24cSRui Ueyama 
4563837f427SRui Ueyama     script->phdrsCommands.push_back(cmd);
4572ec34544SRui Ueyama   }
4582ec34544SRui Ueyama }
4592ec34544SRui Ueyama 
4605f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4615f37541cSGeorge Rimar   expect("(");
4623837f427SRui Ueyama   StringRef alias = unquote(next());
4635f37541cSGeorge Rimar   expect(",");
4643837f427SRui Ueyama   StringRef name = next();
4655f37541cSGeorge Rimar   expect(")");
4665f37541cSGeorge Rimar 
4673837f427SRui Ueyama   if (script->memoryRegions.count(alias))
4683837f427SRui Ueyama     setError("redefinition of memory region '" + alias + "'");
4693837f427SRui Ueyama   if (!script->memoryRegions.count(name))
4703837f427SRui Ueyama     setError("memory region '" + name + "' is not defined");
4713837f427SRui Ueyama   script->memoryRegions.insert({alias, script->memoryRegions[name]});
4725f37541cSGeorge Rimar }
4735f37541cSGeorge Rimar 
4742ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4752ec34544SRui Ueyama   expect("(");
4763837f427SRui Ueyama   StringRef tok = next();
4773837f427SRui Ueyama   if (!config->nostdlib)
4783837f427SRui Ueyama     config->searchPaths.push_back(unquote(tok));
4792ec34544SRui Ueyama   expect(")");
4802ec34544SRui Ueyama }
4812ec34544SRui Ueyama 
482a582419aSGeorge Rimar // This reads an overlay description. Overlays are used to describe output
483a582419aSGeorge Rimar // sections that use the same virtual memory range and normally would trigger
484a582419aSGeorge Rimar // linker's sections sanity check failures.
485a582419aSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
486a582419aSGeorge Rimar std::vector<BaseCommand *> ScriptParser::readOverlay() {
487a582419aSGeorge Rimar   // VA and LMA expressions are optional, though for simplicity of
488a582419aSGeorge Rimar   // implementation we assume they are not. That is what OVERLAY was designed
489a582419aSGeorge Rimar   // for first of all: to allow sections with overlapping VAs at different LMAs.
4903837f427SRui Ueyama   Expr addrExpr = readExpr();
491a582419aSGeorge Rimar   expect(":");
492a582419aSGeorge Rimar   expect("AT");
4933837f427SRui Ueyama   Expr lmaExpr = readParenExpr();
494a582419aSGeorge Rimar   expect("{");
495a582419aSGeorge Rimar 
4963837f427SRui Ueyama   std::vector<BaseCommand *> v;
4973837f427SRui Ueyama   OutputSection *prev = nullptr;
498a582419aSGeorge Rimar   while (!errorCount() && !consume("}")) {
499a582419aSGeorge Rimar     // VA is the same for all sections. The LMAs are consecutive in memory
500a582419aSGeorge Rimar     // starting from the base load address specified.
5013837f427SRui Ueyama     OutputSection *os = readOverlaySectionDescription();
5023837f427SRui Ueyama     os->addrExpr = addrExpr;
5033837f427SRui Ueyama     if (prev)
5043837f427SRui Ueyama       os->lmaExpr = [=] { return prev->getLMA() + prev->size; };
505a582419aSGeorge Rimar     else
5063837f427SRui Ueyama       os->lmaExpr = lmaExpr;
5073837f427SRui Ueyama     v.push_back(os);
5083837f427SRui Ueyama     prev = os;
509a582419aSGeorge Rimar   }
510a582419aSGeorge Rimar 
511a582419aSGeorge Rimar   // According to the specification, at the end of the overlay, the location
512a582419aSGeorge Rimar   // counter should be equal to the overlay base address plus size of the
513a582419aSGeorge Rimar   // largest section seen in the overlay.
514a582419aSGeorge Rimar   // Here we want to create the Dot assignment command to achieve that.
5153837f427SRui Ueyama   Expr moveDot = [=] {
5163837f427SRui Ueyama     uint64_t max = 0;
5173837f427SRui Ueyama     for (BaseCommand *cmd : v)
5183837f427SRui Ueyama       max = std::max(max, cast<OutputSection>(cmd)->size);
5193837f427SRui Ueyama     return addrExpr().getValue() + max;
520a582419aSGeorge Rimar   };
5213837f427SRui Ueyama   v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation()));
5223837f427SRui Ueyama   return v;
523a582419aSGeorge Rimar }
524a582419aSGeorge Rimar 
5252ec34544SRui Ueyama void ScriptParser::readSections() {
5262ec34544SRui Ueyama   expect("{");
5273837f427SRui Ueyama   std::vector<BaseCommand *> v;
528b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
5293837f427SRui Ueyama     StringRef tok = next();
5303837f427SRui Ueyama     if (tok == "OVERLAY") {
5313837f427SRui Ueyama       for (BaseCommand *cmd : readOverlay())
5323837f427SRui Ueyama         v.push_back(cmd);
533a582419aSGeorge Rimar       continue;
5343837f427SRui Ueyama     } else if (tok == "INCLUDE") {
5352e9d40d5SRui Ueyama       readInclude();
5362e9d40d5SRui Ueyama       continue;
537a582419aSGeorge Rimar     }
538a582419aSGeorge Rimar 
5393837f427SRui Ueyama     if (BaseCommand *cmd = readAssignment(tok))
5403837f427SRui Ueyama       v.push_back(cmd);
541d30a78b3SGeorge Rimar     else
5423837f427SRui Ueyama       v.push_back(readOutputSectionDescription(tok));
5432ec34544SRui Ueyama   }
5447c426fb1SFangrui Song   script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),
5457c426fb1SFangrui Song                                  v.end());
5469e2c8a9dSGeorge Rimar 
5477c426fb1SFangrui Song   if (atEOF() || !consume("INSERT")) {
5487c426fb1SFangrui Song     script->hasSectionsCommand = true;
5499e2c8a9dSGeorge Rimar     return;
5509e2c8a9dSGeorge Rimar   }
5519e2c8a9dSGeorge Rimar 
5527c426fb1SFangrui Song   bool isAfter = false;
5537c426fb1SFangrui Song   if (consume("AFTER"))
5547c426fb1SFangrui Song     isAfter = true;
5557c426fb1SFangrui Song   else if (!consume("BEFORE"))
5567c426fb1SFangrui Song     setError("expected AFTER/BEFORE, but got '" + next() + "'");
5577c426fb1SFangrui Song   StringRef where = next();
5587c426fb1SFangrui Song   for (BaseCommand *cmd : v)
5597c426fb1SFangrui Song     if (auto *os = dyn_cast<OutputSection>(cmd))
5607c426fb1SFangrui Song       script->insertCommands.push_back({os, isAfter, where});
5612ec34544SRui Ueyama }
5622ec34544SRui Ueyama 
563e262bb1aSRui Ueyama void ScriptParser::readTarget() {
564e262bb1aSRui Ueyama   // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
565e262bb1aSRui Ueyama   // we accept only a limited set of BFD names (i.e. "elf" or "binary")
566e262bb1aSRui Ueyama   // for --format. We recognize only /^elf/ and "binary" in the linker
567e262bb1aSRui Ueyama   // script as well.
568e262bb1aSRui Ueyama   expect("(");
5693837f427SRui Ueyama   StringRef tok = next();
570e262bb1aSRui Ueyama   expect(")");
571e262bb1aSRui Ueyama 
5723837f427SRui Ueyama   if (tok.startswith("elf"))
5733837f427SRui Ueyama     config->formatBinary = false;
5743837f427SRui Ueyama   else if (tok == "binary")
5753837f427SRui Ueyama     config->formatBinary = true;
576e262bb1aSRui Ueyama   else
5773837f427SRui Ueyama     setError("unknown target: " + tok);
578e262bb1aSRui Ueyama }
579e262bb1aSRui Ueyama 
5803837f427SRui Ueyama static int precedence(StringRef op) {
5813837f427SRui Ueyama   return StringSwitch<int>(op)
582a5005482SGeorge Rimar       .Cases("*", "/", "%", 8)
583a5005482SGeorge Rimar       .Cases("+", "-", 7)
584a5005482SGeorge Rimar       .Cases("<<", ">>", 6)
585a5005482SGeorge Rimar       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
586a5005482SGeorge Rimar       .Case("&", 4)
587a5005482SGeorge Rimar       .Case("|", 3)
588a5005482SGeorge Rimar       .Case("&&", 2)
589a5005482SGeorge Rimar       .Case("||", 1)
5902ec34544SRui Ueyama       .Default(-1);
5912ec34544SRui Ueyama }
5922ec34544SRui Ueyama 
5932ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
594c42fe247SThomas Preud'homme   StringMatcher Matcher;
595c42fe247SThomas Preud'homme 
596b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
597c42fe247SThomas Preud'homme     Matcher.addPattern(SingleStringMatcher(next()));
598c42fe247SThomas Preud'homme   return Matcher;
5992ec34544SRui Ueyama }
6002ec34544SRui Ueyama 
6012ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
6022ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
6032ec34544SRui Ueyama     return SortSectionPolicy::Name;
6042ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
6052ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
6062ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
6072ec34544SRui Ueyama     return SortSectionPolicy::Priority;
6082ec34544SRui Ueyama   if (consume("SORT_NONE"))
6092ec34544SRui Ueyama     return SortSectionPolicy::None;
6102ec34544SRui Ueyama   return SortSectionPolicy::Default;
6112ec34544SRui Ueyama }
6122ec34544SRui Ueyama 
61303fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
61403fc8d1eSRui Ueyama //
61503fc8d1eSRui Ueyama // <contents> ::= <elem>*
61603fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
61703fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
61803fc8d1eSRui Ueyama //
61903fc8d1eSRui Ueyama // For example,
62003fc8d1eSRui Ueyama //
62103fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
62203fc8d1eSRui Ueyama //
62303fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
62403fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
62503fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
6262ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
6273837f427SRui Ueyama   std::vector<SectionPattern> ret;
628b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
6293837f427SRui Ueyama     StringMatcher excludeFilePat;
6302ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
6312ec34544SRui Ueyama       expect("(");
6323837f427SRui Ueyama       excludeFilePat = readFilePatterns();
6332ec34544SRui Ueyama     }
6342ec34544SRui Ueyama 
635c42fe247SThomas Preud'homme     StringMatcher SectionMatcher;
636b8a59c8aSBob Haarman     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
637c42fe247SThomas Preud'homme       SectionMatcher.addPattern(unquote(next()));
6382ec34544SRui Ueyama 
639c42fe247SThomas Preud'homme     if (!SectionMatcher.empty())
640c42fe247SThomas Preud'homme       ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
6412ec34544SRui Ueyama     else
6422ec34544SRui Ueyama       setError("section pattern is expected");
6432ec34544SRui Ueyama   }
6443837f427SRui Ueyama   return ret;
6452ec34544SRui Ueyama }
6462ec34544SRui Ueyama 
6472ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
6482ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
6492ec34544SRui Ueyama //
6502ec34544SRui Ueyama // <patterns> ::= <section-list>
6512ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
6522ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
6532ec34544SRui Ueyama //
6542ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
6552ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
6562ec34544SRui Ueyama //
6572ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
6582ec34544SRui Ueyama InputSectionDescription *
659dbd0ad33SPeter Smith ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
660dbd0ad33SPeter Smith                                     uint64_t withoutFlags) {
661dbd0ad33SPeter Smith   auto *cmd =
662dbd0ad33SPeter Smith       make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
6632ec34544SRui Ueyama   expect("(");
6642ec34544SRui Ueyama 
665b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
6663837f427SRui Ueyama     SortSectionPolicy outer = readSortKind();
6673837f427SRui Ueyama     SortSectionPolicy inner = SortSectionPolicy::Default;
6683837f427SRui Ueyama     std::vector<SectionPattern> v;
6693837f427SRui Ueyama     if (outer != SortSectionPolicy::Default) {
6702ec34544SRui Ueyama       expect("(");
6713837f427SRui Ueyama       inner = readSortKind();
6723837f427SRui Ueyama       if (inner != SortSectionPolicy::Default) {
6732ec34544SRui Ueyama         expect("(");
6743837f427SRui Ueyama         v = readInputSectionsList();
6752ec34544SRui Ueyama         expect(")");
6762ec34544SRui Ueyama       } else {
6773837f427SRui Ueyama         v = readInputSectionsList();
6782ec34544SRui Ueyama       }
6792ec34544SRui Ueyama       expect(")");
6802ec34544SRui Ueyama     } else {
6813837f427SRui Ueyama       v = readInputSectionsList();
6822ec34544SRui Ueyama     }
6832ec34544SRui Ueyama 
6843837f427SRui Ueyama     for (SectionPattern &pat : v) {
6853837f427SRui Ueyama       pat.sortInner = inner;
6863837f427SRui Ueyama       pat.sortOuter = outer;
6872ec34544SRui Ueyama     }
6882ec34544SRui Ueyama 
6893837f427SRui Ueyama     std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
6902ec34544SRui Ueyama   }
6913837f427SRui Ueyama   return cmd;
6922ec34544SRui Ueyama }
6932ec34544SRui Ueyama 
6942ec34544SRui Ueyama InputSectionDescription *
6953837f427SRui Ueyama ScriptParser::readInputSectionDescription(StringRef tok) {
6962ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
6972ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
698dbd0ad33SPeter Smith   uint64_t withFlags = 0;
699dbd0ad33SPeter Smith   uint64_t withoutFlags = 0;
7003837f427SRui Ueyama   if (tok == "KEEP") {
7012ec34544SRui Ueyama     expect("(");
702dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
703dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
704dbd0ad33SPeter Smith     InputSectionDescription *cmd =
705dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags);
7062ec34544SRui Ueyama     expect(")");
7073837f427SRui Ueyama     script->keptSections.push_back(cmd);
7083837f427SRui Ueyama     return cmd;
7092ec34544SRui Ueyama   }
710dbd0ad33SPeter Smith   if (tok == "INPUT_SECTION_FLAGS") {
711dbd0ad33SPeter Smith     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
712dbd0ad33SPeter Smith     tok = next();
713dbd0ad33SPeter Smith   }
714dbd0ad33SPeter Smith   return readInputSectionRules(tok, withFlags, withoutFlags);
7152ec34544SRui Ueyama }
7162ec34544SRui Ueyama 
7172ec34544SRui Ueyama void ScriptParser::readSort() {
7182ec34544SRui Ueyama   expect("(");
7192ec34544SRui Ueyama   expect("CONSTRUCTORS");
7202ec34544SRui Ueyama   expect(")");
7212ec34544SRui Ueyama }
7222ec34544SRui Ueyama 
723d30a78b3SGeorge Rimar Expr ScriptParser::readAssert() {
7242ec34544SRui Ueyama   expect("(");
7253837f427SRui Ueyama   Expr e = readExpr();
7262ec34544SRui Ueyama   expect(",");
7273837f427SRui Ueyama   StringRef msg = unquote(next());
7282ec34544SRui Ueyama   expect(")");
729b579c439SRui Ueyama 
7302ec34544SRui Ueyama   return [=] {
7313837f427SRui Ueyama     if (!e().getValue())
7322682bc3cSFangrui Song       errorOrWarn(msg);
7333837f427SRui Ueyama     return script->getDot();
7342ec34544SRui Ueyama   };
7352ec34544SRui Ueyama }
7362ec34544SRui Ueyama 
737a46d08ebSGeorge Rimar // Tries to read the special directive for an output section definition which
738a46d08ebSGeorge Rimar // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
739a46d08ebSGeorge Rimar // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
7403837f427SRui Ueyama bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) {
7413837f427SRui Ueyama   if (tok1 != "(")
742a46d08ebSGeorge Rimar     return false;
7433837f427SRui Ueyama   if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" && tok2 != "OVERLAY")
744a46d08ebSGeorge Rimar     return false;
745a46d08ebSGeorge Rimar 
746a46d08ebSGeorge Rimar   expect("(");
747a46d08ebSGeorge Rimar   if (consume("NOLOAD")) {
7483837f427SRui Ueyama     cmd->noload = true;
749*fdc41aa2SMatt Schulte     cmd->type = SHT_NOBITS;
750a46d08ebSGeorge Rimar   } else {
751a46d08ebSGeorge Rimar     skip(); // This is "COPY", "INFO" or "OVERLAY".
7523837f427SRui Ueyama     cmd->nonAlloc = true;
753a46d08ebSGeorge Rimar   }
754a46d08ebSGeorge Rimar   expect(")");
755a46d08ebSGeorge Rimar   return true;
756a46d08ebSGeorge Rimar }
757a46d08ebSGeorge Rimar 
7581c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
7591c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
7601c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
7613271d370SRui Ueyama //
7623271d370SRui Ueyama // An output section name can be followed by an address expression
7631c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
76497f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
7651c08e9f5SGeorge Rimar // of directive.
7663271d370SRui Ueyama //
767b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
768fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
7693837f427SRui Ueyama void ScriptParser::readSectionAddressType(OutputSection *cmd) {
7703837f427SRui Ueyama   if (readSectionDirective(cmd, peek(), peek2()))
7713271d370SRui Ueyama     return;
7723271d370SRui Ueyama 
7733837f427SRui Ueyama   cmd->addrExpr = readExpr();
7743837f427SRui Ueyama   if (peek() == "(" && !readSectionDirective(cmd, "(", peek2()))
775a46d08ebSGeorge Rimar     setError("unknown section directive: " + peek2());
776fbb0463fSGeorge Rimar }
777fbb0463fSGeorge Rimar 
7783837f427SRui Ueyama static Expr checkAlignment(Expr e, std::string &loc) {
779f22ec9ddSGeorge Rimar   return [=] {
7803837f427SRui Ueyama     uint64_t alignment = std::max((uint64_t)1, e().getValue());
7813837f427SRui Ueyama     if (!isPowerOf2_64(alignment)) {
7823837f427SRui Ueyama       error(loc + ": alignment must be power of 2");
783f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
784f22ec9ddSGeorge Rimar     }
7853837f427SRui Ueyama     return alignment;
786f22ec9ddSGeorge Rimar   };
787f22ec9ddSGeorge Rimar }
788f22ec9ddSGeorge Rimar 
789a582419aSGeorge Rimar OutputSection *ScriptParser::readOverlaySectionDescription() {
7903837f427SRui Ueyama   OutputSection *cmd =
7913837f427SRui Ueyama       script->createOutputSection(next(), getCurrentLocation());
7923837f427SRui Ueyama   cmd->inOverlay = true;
793a582419aSGeorge Rimar   expect("{");
794dbd0ad33SPeter Smith   while (!errorCount() && !consume("}")) {
795dbd0ad33SPeter Smith     uint64_t withFlags = 0;
796dbd0ad33SPeter Smith     uint64_t withoutFlags = 0;
797dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
798dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
799dbd0ad33SPeter Smith     cmd->sectionCommands.push_back(
800dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags));
801dbd0ad33SPeter Smith   }
8023837f427SRui Ueyama   return cmd;
803a582419aSGeorge Rimar }
804a582419aSGeorge Rimar 
8053837f427SRui Ueyama OutputSection *ScriptParser::readOutputSectionDescription(StringRef outSec) {
8063837f427SRui Ueyama   OutputSection *cmd =
8073837f427SRui Ueyama       script->createOutputSection(outSec, getCurrentLocation());
8083271d370SRui Ueyama 
8093837f427SRui Ueyama   size_t symbolsReferenced = script->referencedSymbols.size();
810c4df670dSGeorge Rimar 
8113271d370SRui Ueyama   if (peek() != ":")
8123837f427SRui Ueyama     readSectionAddressType(cmd);
8132ec34544SRui Ueyama   expect(":");
8142ec34544SRui Ueyama 
8153837f427SRui Ueyama   std::string location = getCurrentLocation();
8162ec34544SRui Ueyama   if (consume("AT"))
8173837f427SRui Ueyama     cmd->lmaExpr = readParenExpr();
8182ec34544SRui Ueyama   if (consume("ALIGN"))
8193837f427SRui Ueyama     cmd->alignExpr = checkAlignment(readParenExpr(), location);
8202ec34544SRui Ueyama   if (consume("SUBALIGN"))
8213837f427SRui Ueyama     cmd->subalignExpr = checkAlignment(readParenExpr(), location);
8222ec34544SRui Ueyama 
8232ec34544SRui Ueyama   // Parse constraints.
8242ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
8253837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadOnly;
8262ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
8273837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadWrite;
8282ec34544SRui Ueyama   expect("{");
8292ec34544SRui Ueyama 
830b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
8313837f427SRui Ueyama     StringRef tok = next();
8323837f427SRui Ueyama     if (tok == ";") {
8332ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
8343837f427SRui Ueyama     } else if (SymbolAssignment *assign = readAssignment(tok)) {
8353837f427SRui Ueyama       cmd->sectionCommands.push_back(assign);
8363837f427SRui Ueyama     } else if (ByteCommand *data = readByteCommand(tok)) {
8373837f427SRui Ueyama       cmd->sectionCommands.push_back(data);
8383837f427SRui Ueyama     } else if (tok == "CONSTRUCTORS") {
8392ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
8402ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
8412ec34544SRui Ueyama       // For ELF, we should ignore.
8423837f427SRui Ueyama     } else if (tok == "FILL") {
8430810f16fSGeorge Rimar       // We handle the FILL command as an alias for =fillexp section attribute,
8440810f16fSGeorge Rimar       // which is different from what GNU linkers do.
8450810f16fSGeorge Rimar       // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
846bb7d2b17SGeorgii Rymar       if (peek() != "(")
847bb7d2b17SGeorgii Rymar         setError("( expected, but got " + peek());
8483837f427SRui Ueyama       cmd->filler = readFill();
8493837f427SRui Ueyama     } else if (tok == "SORT") {
8502ec34544SRui Ueyama       readSort();
8513837f427SRui Ueyama     } else if (tok == "INCLUDE") {
8522e9d40d5SRui Ueyama       readInclude();
8532ec34544SRui Ueyama     } else if (peek() == "(") {
8543837f427SRui Ueyama       cmd->sectionCommands.push_back(readInputSectionDescription(tok));
8552ec34544SRui Ueyama     } else {
856f49fe218SGeorge Rimar       // We have a file name and no input sections description. It is not a
857f49fe218SGeorge Rimar       // commonly used syntax, but still acceptable. In that case, all sections
858f49fe218SGeorge Rimar       // from the file will be included.
859dbd0ad33SPeter Smith       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
860dbd0ad33SPeter Smith       // handle this case here as it will already have been matched by the
861dbd0ad33SPeter Smith       // case above.
8623837f427SRui Ueyama       auto *isd = make<InputSectionDescription>(tok);
863c42fe247SThomas Preud'homme       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
8643837f427SRui Ueyama       cmd->sectionCommands.push_back(isd);
8652ec34544SRui Ueyama     }
8662ec34544SRui Ueyama   }
8672ec34544SRui Ueyama 
8682ec34544SRui Ueyama   if (consume(">"))
869adcd0268SBenjamin Kramer     cmd->memoryRegionName = std::string(next());
8702ec34544SRui Ueyama 
8715d01a8beSGeorge Rimar   if (consume("AT")) {
8725d01a8beSGeorge Rimar     expect(">");
873adcd0268SBenjamin Kramer     cmd->lmaRegionName = std::string(next());
8745d01a8beSGeorge Rimar   }
8755d01a8beSGeorge Rimar 
8763837f427SRui Ueyama   if (cmd->lmaExpr && !cmd->lmaRegionName.empty())
8775d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
8785d01a8beSGeorge Rimar 
8793837f427SRui Ueyama   cmd->phdrs = readOutputSectionPhdrs();
8802ec34544SRui Ueyama 
8810810f16fSGeorge Rimar   if (peek() == "=" || peek().startswith("=")) {
8823837f427SRui Ueyama     inExpr = true;
8830810f16fSGeorge Rimar     consume("=");
8843837f427SRui Ueyama     cmd->filler = readFill();
8853837f427SRui Ueyama     inExpr = false;
8860810f16fSGeorge Rimar   }
8872ec34544SRui Ueyama 
8882ec34544SRui Ueyama   // Consume optional comma following output section command.
8892ec34544SRui Ueyama   consume(",");
8902ec34544SRui Ueyama 
8913837f427SRui Ueyama   if (script->referencedSymbols.size() > symbolsReferenced)
8923837f427SRui Ueyama     cmd->expressionsUseSymbols = true;
8933837f427SRui Ueyama   return cmd;
8942ec34544SRui Ueyama }
8952ec34544SRui Ueyama 
8960810f16fSGeorge Rimar // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
8972ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
8980810f16fSGeorge Rimar // We do not support using symbols in such expressions.
8992ec34544SRui Ueyama //
9008acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
9018acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
9028acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
903bb7d2b17SGeorgii Rymar // Also, we require that expressions with operators must be wrapped into
904bb7d2b17SGeorgii Rymar // round brackets. We did it to resolve the ambiguity when parsing scripts like:
905bb7d2b17SGeorgii Rymar // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
9060810f16fSGeorge Rimar std::array<uint8_t, 4> ScriptParser::readFill() {
907bb7d2b17SGeorgii Rymar   uint64_t value = readPrimary()().val;
9083837f427SRui Ueyama   if (value > UINT32_MAX)
9090810f16fSGeorge Rimar     setError("filler expression result does not fit 32-bit: 0x" +
9103837f427SRui Ueyama              Twine::utohexstr(value));
911b58079d4SRui Ueyama 
9123837f427SRui Ueyama   std::array<uint8_t, 4> buf;
9133837f427SRui Ueyama   write32be(buf.data(), (uint32_t)value);
9143837f427SRui Ueyama   return buf;
9152ec34544SRui Ueyama }
9162ec34544SRui Ueyama 
9173837f427SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
9182ec34544SRui Ueyama   expect("(");
9193837f427SRui Ueyama   SymbolAssignment *cmd = readSymbolAssignment(next());
9203837f427SRui Ueyama   cmd->provide = provide;
9213837f427SRui Ueyama   cmd->hidden = hidden;
9222ec34544SRui Ueyama   expect(")");
9233837f427SRui Ueyama   return cmd;
9242ec34544SRui Ueyama }
9252ec34544SRui Ueyama 
9263837f427SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
927d30a78b3SGeorge Rimar   // Assert expression returns Dot, so this is equal to ".=."
9283837f427SRui Ueyama   if (tok == "ASSERT")
929d30a78b3SGeorge Rimar     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
930d30a78b3SGeorge Rimar 
9313837f427SRui Ueyama   size_t oldPos = pos;
9323837f427SRui Ueyama   SymbolAssignment *cmd = nullptr;
933e88b76a9SGeorge Rimar   if (peek() == "=" || peek() == "+=")
9343837f427SRui Ueyama     cmd = readSymbolAssignment(tok);
9353837f427SRui Ueyama   else if (tok == "PROVIDE")
9363837f427SRui Ueyama     cmd = readProvideHidden(true, false);
9373837f427SRui Ueyama   else if (tok == "HIDDEN")
9383837f427SRui Ueyama     cmd = readProvideHidden(false, true);
9393837f427SRui Ueyama   else if (tok == "PROVIDE_HIDDEN")
9403837f427SRui Ueyama     cmd = readProvideHidden(true, true);
941e88b76a9SGeorge Rimar 
9423837f427SRui Ueyama   if (cmd) {
9433837f427SRui Ueyama     cmd->commandString =
9443837f427SRui Ueyama         tok.str() + " " +
9453837f427SRui Ueyama         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
946e88b76a9SGeorge Rimar     expect(";");
9472ec34544SRui Ueyama   }
9483837f427SRui Ueyama   return cmd;
9492ec34544SRui Ueyama }
9502ec34544SRui Ueyama 
9513837f427SRui Ueyama SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
9523837f427SRui Ueyama   StringRef op = next();
9533837f427SRui Ueyama   assert(op == "=" || op == "+=");
9543837f427SRui Ueyama   Expr e = readExpr();
9553837f427SRui Ueyama   if (op == "+=") {
9563837f427SRui Ueyama     std::string loc = getCurrentLocation();
9573837f427SRui Ueyama     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
9582ec34544SRui Ueyama   }
9593837f427SRui Ueyama   return make<SymbolAssignment>(name, e, getCurrentLocation());
9602ec34544SRui Ueyama }
9612ec34544SRui Ueyama 
9622ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
9632ec34544SRui Ueyama // script expression.
9642ec34544SRui Ueyama Expr ScriptParser::readExpr() {
9652ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
9662ec34544SRui Ueyama   // they apply different tokenization rules.
9673837f427SRui Ueyama   bool orig = inExpr;
9683837f427SRui Ueyama   inExpr = true;
9693837f427SRui Ueyama   Expr e = readExpr1(readPrimary(), 0);
9703837f427SRui Ueyama   inExpr = orig;
9713837f427SRui Ueyama   return e;
9722ec34544SRui Ueyama }
9732ec34544SRui Ueyama 
9743837f427SRui Ueyama Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
9753837f427SRui Ueyama   if (op == "+")
9763837f427SRui Ueyama     return [=] { return add(l(), r()); };
9773837f427SRui Ueyama   if (op == "-")
9783837f427SRui Ueyama     return [=] { return sub(l(), r()); };
9793837f427SRui Ueyama   if (op == "*")
9803837f427SRui Ueyama     return [=] { return l().getValue() * r().getValue(); };
9813837f427SRui Ueyama   if (op == "/") {
9823837f427SRui Ueyama     std::string loc = getCurrentLocation();
9837b91e213SGeorge Rimar     return [=]() -> uint64_t {
9843837f427SRui Ueyama       if (uint64_t rv = r().getValue())
9853837f427SRui Ueyama         return l().getValue() / rv;
9863837f427SRui Ueyama       error(loc + ": division by zero");
987067617f9SRui Ueyama       return 0;
9887b91e213SGeorge Rimar     };
9897b91e213SGeorge Rimar   }
9903837f427SRui Ueyama   if (op == "%") {
9913837f427SRui Ueyama     std::string loc = getCurrentLocation();
9927b91e213SGeorge Rimar     return [=]() -> uint64_t {
9933837f427SRui Ueyama       if (uint64_t rv = r().getValue())
9943837f427SRui Ueyama         return l().getValue() % rv;
9953837f427SRui Ueyama       error(loc + ": modulo by zero");
996067617f9SRui Ueyama       return 0;
9977b91e213SGeorge Rimar     };
9987b91e213SGeorge Rimar   }
9993837f427SRui Ueyama   if (op == "<<")
10003837f427SRui Ueyama     return [=] { return l().getValue() << r().getValue(); };
10013837f427SRui Ueyama   if (op == ">>")
10023837f427SRui Ueyama     return [=] { return l().getValue() >> r().getValue(); };
10033837f427SRui Ueyama   if (op == "<")
10043837f427SRui Ueyama     return [=] { return l().getValue() < r().getValue(); };
10053837f427SRui Ueyama   if (op == ">")
10063837f427SRui Ueyama     return [=] { return l().getValue() > r().getValue(); };
10073837f427SRui Ueyama   if (op == ">=")
10083837f427SRui Ueyama     return [=] { return l().getValue() >= r().getValue(); };
10093837f427SRui Ueyama   if (op == "<=")
10103837f427SRui Ueyama     return [=] { return l().getValue() <= r().getValue(); };
10113837f427SRui Ueyama   if (op == "==")
10123837f427SRui Ueyama     return [=] { return l().getValue() == r().getValue(); };
10133837f427SRui Ueyama   if (op == "!=")
10143837f427SRui Ueyama     return [=] { return l().getValue() != r().getValue(); };
10153837f427SRui Ueyama   if (op == "||")
10163837f427SRui Ueyama     return [=] { return l().getValue() || r().getValue(); };
10173837f427SRui Ueyama   if (op == "&&")
10183837f427SRui Ueyama     return [=] { return l().getValue() && r().getValue(); };
10193837f427SRui Ueyama   if (op == "&")
10203837f427SRui Ueyama     return [=] { return bitAnd(l(), r()); };
10213837f427SRui Ueyama   if (op == "|")
10223837f427SRui Ueyama     return [=] { return bitOr(l(), r()); };
10232ec34544SRui Ueyama   llvm_unreachable("invalid operator");
10242ec34544SRui Ueyama }
10252ec34544SRui Ueyama 
10262ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
10272ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
10283837f427SRui Ueyama Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1029b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
10302ec34544SRui Ueyama     // Read an operator and an expression.
10312ec34544SRui Ueyama     if (consume("?"))
10323837f427SRui Ueyama       return readTernary(lhs);
10333837f427SRui Ueyama     StringRef op1 = peek();
10343837f427SRui Ueyama     if (precedence(op1) < minPrec)
10352ec34544SRui Ueyama       break;
10362ec34544SRui Ueyama     skip();
10373837f427SRui Ueyama     Expr rhs = readPrimary();
10382ec34544SRui Ueyama 
10392ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
10402ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
10412ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
10422ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
10432ec34544SRui Ueyama     while (!atEOF()) {
10443837f427SRui Ueyama       StringRef op2 = peek();
10453837f427SRui Ueyama       if (precedence(op2) <= precedence(op1))
10462ec34544SRui Ueyama         break;
10473837f427SRui Ueyama       rhs = readExpr1(rhs, precedence(op2));
10482ec34544SRui Ueyama     }
10492ec34544SRui Ueyama 
10503837f427SRui Ueyama     lhs = combine(op1, lhs, rhs);
10512ec34544SRui Ueyama   }
10523837f427SRui Ueyama   return lhs;
10532ec34544SRui Ueyama }
10542ec34544SRui Ueyama 
10555fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
10563837f427SRui Ueyama   std::string location = getCurrentLocation();
10575fb17128SGeorge Rimar   return [=]() -> uint64_t {
10583837f427SRui Ueyama     if (target)
10593837f427SRui Ueyama       return config->commonPageSize;
10603837f427SRui Ueyama     error(location + ": unable to calculate page size");
10615fb17128SGeorge Rimar     return 4096; // Return a dummy value.
10625fb17128SGeorge Rimar   };
10635fb17128SGeorge Rimar }
10645fb17128SGeorge Rimar 
10655fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
10663837f427SRui Ueyama   StringRef s = readParenLiteral();
10673837f427SRui Ueyama   if (s == "COMMONPAGESIZE")
10685fb17128SGeorge Rimar     return getPageSize();
10693837f427SRui Ueyama   if (s == "MAXPAGESIZE")
10703837f427SRui Ueyama     return [] { return config->maxPageSize; };
10713837f427SRui Ueyama   setError("unknown constant: " + s);
1072b068b037SGeorge Rimar   return [] { return 0; };
10732ec34544SRui Ueyama }
10742ec34544SRui Ueyama 
10755c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
10765c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
10775c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
10783837f427SRui Ueyama static Optional<uint64_t> parseInt(StringRef tok) {
10792ec34544SRui Ueyama   // Hexadecimal
10803837f427SRui Ueyama   uint64_t val;
10813837f427SRui Ueyama   if (tok.startswith_lower("0x")) {
10823837f427SRui Ueyama     if (!to_integer(tok.substr(2), val, 16))
10834092016bSRui Ueyama       return None;
10843837f427SRui Ueyama     return val;
10854092016bSRui Ueyama   }
10863837f427SRui Ueyama   if (tok.endswith_lower("H")) {
10873837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 16))
10884092016bSRui Ueyama       return None;
10893837f427SRui Ueyama     return val;
10904092016bSRui Ueyama   }
10912ec34544SRui Ueyama 
10922ec34544SRui Ueyama   // Decimal
10933837f427SRui Ueyama   if (tok.endswith_lower("K")) {
10943837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
10955c65088fSRui Ueyama       return None;
10963837f427SRui Ueyama     return val * 1024;
10972ec34544SRui Ueyama   }
10983837f427SRui Ueyama   if (tok.endswith_lower("M")) {
10993837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
11005c65088fSRui Ueyama       return None;
11013837f427SRui Ueyama     return val * 1024 * 1024;
11025c65088fSRui Ueyama   }
11033837f427SRui Ueyama   if (!to_integer(tok, val, 10))
11045c65088fSRui Ueyama     return None;
11053837f427SRui Ueyama   return val;
11062ec34544SRui Ueyama }
11072ec34544SRui Ueyama 
11083837f427SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
11093837f427SRui Ueyama   int size = StringSwitch<int>(tok)
11102ec34544SRui Ueyama                  .Case("BYTE", 1)
11112ec34544SRui Ueyama                  .Case("SHORT", 2)
11122ec34544SRui Ueyama                  .Case("LONG", 4)
11132ec34544SRui Ueyama                  .Case("QUAD", 8)
11142ec34544SRui Ueyama                  .Default(-1);
11153837f427SRui Ueyama   if (size == -1)
11162ec34544SRui Ueyama     return nullptr;
111784bcabcbSGeorge Rimar 
11183837f427SRui Ueyama   size_t oldPos = pos;
11193837f427SRui Ueyama   Expr e = readParenExpr();
11203837f427SRui Ueyama   std::string commandString =
11213837f427SRui Ueyama       tok.str() + " " +
11223837f427SRui Ueyama       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
11233837f427SRui Ueyama   return make<ByteCommand>(e, size, commandString);
11242ec34544SRui Ueyama }
11252ec34544SRui Ueyama 
1126dbd0ad33SPeter Smith static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1127dbd0ad33SPeter Smith   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1128dbd0ad33SPeter Smith     return asInt;
1129dbd0ad33SPeter Smith #define CASE_ENT(enum) #enum, ELF::enum
1130dbd0ad33SPeter Smith   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1131dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_WRITE))
1132dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ALLOC))
1133dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXECINSTR))
1134dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_MERGE))
1135dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_STRINGS))
1136dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_INFO_LINK))
1137dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_LINK_ORDER))
1138dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1139dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_GROUP))
1140dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_TLS))
1141dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_COMPRESSED))
1142dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXCLUDE))
1143dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ARM_PURECODE))
1144dbd0ad33SPeter Smith       .Default(None);
1145dbd0ad33SPeter Smith #undef CASE_ENT
1146dbd0ad33SPeter Smith }
1147dbd0ad33SPeter Smith 
1148dbd0ad33SPeter Smith // Reads the '(' <flags> ')' list of section flags in
1149dbd0ad33SPeter Smith // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1150dbd0ad33SPeter Smith // following form:
1151dbd0ad33SPeter Smith // <flags> ::= <flag>
1152dbd0ad33SPeter Smith //           | <flags> & flag
1153dbd0ad33SPeter Smith // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1154dbd0ad33SPeter Smith // If the first character of <flag> is a ! then this means without flag,
1155dbd0ad33SPeter Smith // otherwise with flag.
1156dbd0ad33SPeter Smith // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1157dbd0ad33SPeter Smith // without flag SHF_WRITE.
1158dbd0ad33SPeter Smith std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1159dbd0ad33SPeter Smith    uint64_t withFlags = 0;
1160dbd0ad33SPeter Smith    uint64_t withoutFlags = 0;
1161dbd0ad33SPeter Smith    expect("(");
1162dbd0ad33SPeter Smith    while (!errorCount()) {
1163dbd0ad33SPeter Smith     StringRef tok = unquote(next());
1164dbd0ad33SPeter Smith     bool without = tok.consume_front("!");
1165dbd0ad33SPeter Smith     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1166dbd0ad33SPeter Smith       if (without)
1167dbd0ad33SPeter Smith         withoutFlags |= *flag;
1168dbd0ad33SPeter Smith       else
1169dbd0ad33SPeter Smith         withFlags |= *flag;
1170dbd0ad33SPeter Smith     } else {
1171dbd0ad33SPeter Smith       setError("unrecognised flag: " + tok);
1172dbd0ad33SPeter Smith     }
1173dbd0ad33SPeter Smith     if (consume(")"))
1174dbd0ad33SPeter Smith       break;
1175dbd0ad33SPeter Smith     if (!consume("&")) {
1176dbd0ad33SPeter Smith       next();
1177dbd0ad33SPeter Smith       setError("expected & or )");
1178dbd0ad33SPeter Smith     }
1179dbd0ad33SPeter Smith   }
1180dbd0ad33SPeter Smith   return std::make_pair(withFlags, withoutFlags);
1181dbd0ad33SPeter Smith }
1182dbd0ad33SPeter Smith 
11832ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
11842ec34544SRui Ueyama   expect("(");
11853837f427SRui Ueyama   bool orig = inExpr;
11863837f427SRui Ueyama   inExpr = false;
11873837f427SRui Ueyama   StringRef tok = next();
11883837f427SRui Ueyama   inExpr = orig;
11892ec34544SRui Ueyama   expect(")");
11903837f427SRui Ueyama   return tok;
11912ec34544SRui Ueyama }
11922ec34544SRui Ueyama 
11933837f427SRui Ueyama static void checkIfExists(OutputSection *cmd, StringRef location) {
11943837f427SRui Ueyama   if (cmd->location.empty() && script->errorOnMissingSection)
11953837f427SRui Ueyama     error(location + ": undefined section " + cmd->name);
119605c4f67cSRafael Espindola }
119705c4f67cSRafael Espindola 
11982ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
11992ec34544SRui Ueyama   if (peek() == "(")
12002ec34544SRui Ueyama     return readParenExpr();
12012ec34544SRui Ueyama 
12025c65088fSRui Ueyama   if (consume("~")) {
12033837f427SRui Ueyama     Expr e = readPrimary();
12043837f427SRui Ueyama     return [=] { return ~e().getValue(); };
12052ec34544SRui Ueyama   }
12066f1d954eSHafiz Abid Qadeer   if (consume("!")) {
12073837f427SRui Ueyama     Expr e = readPrimary();
12083837f427SRui Ueyama     return [=] { return !e().getValue(); };
12096f1d954eSHafiz Abid Qadeer   }
12105c65088fSRui Ueyama   if (consume("-")) {
12113837f427SRui Ueyama     Expr e = readPrimary();
12123837f427SRui Ueyama     return [=] { return -e().getValue(); };
12132ec34544SRui Ueyama   }
12142ec34544SRui Ueyama 
12153837f427SRui Ueyama   StringRef tok = next();
12163837f427SRui Ueyama   std::string location = getCurrentLocation();
12175c65088fSRui Ueyama 
12182ec34544SRui Ueyama   // Built-in functions are parsed here.
12192ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
12203837f427SRui Ueyama   if (tok == "ABSOLUTE") {
12213837f427SRui Ueyama     Expr inner = readParenExpr();
12222ec34544SRui Ueyama     return [=] {
12233837f427SRui Ueyama       ExprValue i = inner();
12243837f427SRui Ueyama       i.forceAbsolute = true;
12253837f427SRui Ueyama       return i;
12262ec34544SRui Ueyama     };
12272ec34544SRui Ueyama   }
12283837f427SRui Ueyama   if (tok == "ADDR") {
12293837f427SRui Ueyama     StringRef name = readParenLiteral();
12303837f427SRui Ueyama     OutputSection *sec = script->getOrCreateOutputSection(name);
12313837f427SRui Ueyama     sec->usedInExpression = true;
123241c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
12333837f427SRui Ueyama       checkIfExists(sec, location);
12343837f427SRui Ueyama       return {sec, false, 0, location};
123541c7ab4aSGeorge Rimar     };
12362ec34544SRui Ueyama   }
12373837f427SRui Ueyama   if (tok == "ALIGN") {
12382ec34544SRui Ueyama     expect("(");
12393837f427SRui Ueyama     Expr e = readExpr();
1240f22ec9ddSGeorge Rimar     if (consume(")")) {
12413837f427SRui Ueyama       e = checkAlignment(e, location);
12423837f427SRui Ueyama       return [=] { return alignTo(script->getDot(), e().getValue()); };
1243f22ec9ddSGeorge Rimar     }
1244b579c439SRui Ueyama     expect(",");
12453837f427SRui Ueyama     Expr e2 = checkAlignment(readExpr(), location);
12462ec34544SRui Ueyama     expect(")");
12473c6de1a6SPetr Hosek     return [=] {
12483837f427SRui Ueyama       ExprValue v = e();
12493837f427SRui Ueyama       v.alignment = e2().getValue();
12503837f427SRui Ueyama       return v;
12513c6de1a6SPetr Hosek     };
12522ec34544SRui Ueyama   }
12533837f427SRui Ueyama   if (tok == "ALIGNOF") {
12543837f427SRui Ueyama     StringRef name = readParenLiteral();
12553837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
1256617e2f98SRui Ueyama     return [=] {
12573837f427SRui Ueyama       checkIfExists(cmd, location);
12583837f427SRui Ueyama       return cmd->alignment;
1259617e2f98SRui Ueyama     };
12602ec34544SRui Ueyama   }
12613837f427SRui Ueyama   if (tok == "ASSERT")
1262d30a78b3SGeorge Rimar     return readAssert();
12633837f427SRui Ueyama   if (tok == "CONSTANT")
12645fb17128SGeorge Rimar     return readConstant();
12653837f427SRui Ueyama   if (tok == "DATA_SEGMENT_ALIGN") {
12662ec34544SRui Ueyama     expect("(");
12673837f427SRui Ueyama     Expr e = readExpr();
12682ec34544SRui Ueyama     expect(",");
12692ec34544SRui Ueyama     readExpr();
12702ec34544SRui Ueyama     expect(")");
127160833f6eSGeorge Rimar     return [=] {
12723837f427SRui Ueyama       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
127360833f6eSGeorge Rimar     };
12742ec34544SRui Ueyama   }
12753837f427SRui Ueyama   if (tok == "DATA_SEGMENT_END") {
12762ec34544SRui Ueyama     expect("(");
12772ec34544SRui Ueyama     expect(".");
12782ec34544SRui Ueyama     expect(")");
12793837f427SRui Ueyama     return [] { return script->getDot(); };
12802ec34544SRui Ueyama   }
12813837f427SRui Ueyama   if (tok == "DATA_SEGMENT_RELRO_END") {
12822ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
12832ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
12842ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
12852ec34544SRui Ueyama     expect("(");
12862ec34544SRui Ueyama     readExpr();
12872ec34544SRui Ueyama     expect(",");
12882ec34544SRui Ueyama     readExpr();
12892ec34544SRui Ueyama     expect(")");
12903837f427SRui Ueyama     Expr e = getPageSize();
12913837f427SRui Ueyama     return [=] { return alignTo(script->getDot(), e().getValue()); };
12922ec34544SRui Ueyama   }
12933837f427SRui Ueyama   if (tok == "DEFINED") {
12943837f427SRui Ueyama     StringRef name = readParenLiteral();
12953837f427SRui Ueyama     return [=] { return symtab->find(name) ? 1 : 0; };
12962ec34544SRui Ueyama   }
12973837f427SRui Ueyama   if (tok == "LENGTH") {
12983837f427SRui Ueyama     StringRef name = readParenLiteral();
12993837f427SRui Ueyama     if (script->memoryRegions.count(name) == 0) {
13003837f427SRui Ueyama       setError("memory region not defined: " + name);
1301b068b037SGeorge Rimar       return [] { return 0; };
1302b068b037SGeorge Rimar     }
130392b5b980SFangrui Song     return script->memoryRegions[name]->length;
130491b95b61SRui Ueyama   }
13053837f427SRui Ueyama   if (tok == "LOADADDR") {
13063837f427SRui Ueyama     StringRef name = readParenLiteral();
13073837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
13083837f427SRui Ueyama     cmd->usedInExpression = true;
1309617e2f98SRui Ueyama     return [=] {
13103837f427SRui Ueyama       checkIfExists(cmd, location);
13113837f427SRui Ueyama       return cmd->getLMA();
1312617e2f98SRui Ueyama     };
13132ec34544SRui Ueyama   }
13143837f427SRui Ueyama   if (tok == "MAX" || tok == "MIN") {
1315fd11560fSGeorge Rimar     expect("(");
13163837f427SRui Ueyama     Expr a = readExpr();
1317fd11560fSGeorge Rimar     expect(",");
13183837f427SRui Ueyama     Expr b = readExpr();
1319fd11560fSGeorge Rimar     expect(")");
13203837f427SRui Ueyama     if (tok == "MIN")
13213837f427SRui Ueyama       return [=] { return std::min(a().getValue(), b().getValue()); };
13223837f427SRui Ueyama     return [=] { return std::max(a().getValue(), b().getValue()); };
1323fd11560fSGeorge Rimar   }
13243837f427SRui Ueyama   if (tok == "ORIGIN") {
13253837f427SRui Ueyama     StringRef name = readParenLiteral();
13263837f427SRui Ueyama     if (script->memoryRegions.count(name) == 0) {
13273837f427SRui Ueyama       setError("memory region not defined: " + name);
1328b068b037SGeorge Rimar       return [] { return 0; };
1329b068b037SGeorge Rimar     }
133092b5b980SFangrui Song     return script->memoryRegions[name]->origin;
133191b95b61SRui Ueyama   }
13323837f427SRui Ueyama   if (tok == "SEGMENT_START") {
13332ec34544SRui Ueyama     expect("(");
13342ec34544SRui Ueyama     skip();
13352ec34544SRui Ueyama     expect(",");
13363837f427SRui Ueyama     Expr e = readExpr();
13372ec34544SRui Ueyama     expect(")");
13383837f427SRui Ueyama     return [=] { return e(); };
13392ec34544SRui Ueyama   }
13403837f427SRui Ueyama   if (tok == "SIZEOF") {
13413837f427SRui Ueyama     StringRef name = readParenLiteral();
13423837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
134305c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
134405c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
134505c4f67cSRafael Espindola     // be empty.
13463837f427SRui Ueyama     return [=] { return cmd->size; };
13472ec34544SRui Ueyama   }
13483837f427SRui Ueyama   if (tok == "SIZEOF_HEADERS")
1349bd8cfe65SFangrui Song     return [=] { return getHeaderSize(); };
13502ec34544SRui Ueyama 
13514eb2eccbSRui Ueyama   // Tok is the dot.
13523837f427SRui Ueyama   if (tok == ".")
13533837f427SRui Ueyama     return [=] { return script->getSymbolValue(tok, location); };
13544eb2eccbSRui Ueyama 
13552ec34544SRui Ueyama   // Tok is a literal number.
13563837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
13573837f427SRui Ueyama     return [=] { return *val; };
13582ec34544SRui Ueyama 
13592ec34544SRui Ueyama   // Tok is a symbol name.
13603837f427SRui Ueyama   if (!isValidCIdentifier(tok))
13613837f427SRui Ueyama     setError("malformed number: " + tok);
13623837f427SRui Ueyama   script->referencedSymbols.push_back(tok);
13633837f427SRui Ueyama   return [=] { return script->getSymbolValue(tok, location); };
13642ec34544SRui Ueyama }
13652ec34544SRui Ueyama 
13663837f427SRui Ueyama Expr ScriptParser::readTernary(Expr cond) {
13673837f427SRui Ueyama   Expr l = readExpr();
13682ec34544SRui Ueyama   expect(":");
13693837f427SRui Ueyama   Expr r = readExpr();
13703837f427SRui Ueyama   return [=] { return cond().getValue() ? l() : r(); };
13712ec34544SRui Ueyama }
13722ec34544SRui Ueyama 
13732ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
13742ec34544SRui Ueyama   expect("(");
13753837f427SRui Ueyama   Expr e = readExpr();
13762ec34544SRui Ueyama   expect(")");
13773837f427SRui Ueyama   return e;
13782ec34544SRui Ueyama }
13792ec34544SRui Ueyama 
13802ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
13813837f427SRui Ueyama   std::vector<StringRef> phdrs;
1382b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
13833837f427SRui Ueyama     StringRef tok = next();
13843837f427SRui Ueyama     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
13852ec34544SRui Ueyama   }
13863837f427SRui Ueyama   return phdrs;
13872ec34544SRui Ueyama }
13882ec34544SRui Ueyama 
13892ec34544SRui Ueyama // Read a program header type name. The next token must be a
13902ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
13912ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
13923837f427SRui Ueyama   StringRef tok = next();
13933837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
13943837f427SRui Ueyama     return *val;
13952ec34544SRui Ueyama 
13963837f427SRui Ueyama   unsigned ret = StringSwitch<unsigned>(tok)
13972ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
13982ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
13992ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
14002ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
14012ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
14022ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
14032ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
14042ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
14052ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
14062ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
14072ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
14082ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
14092ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
14102ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
14112ec34544SRui Ueyama                      .Default(-1);
14122ec34544SRui Ueyama 
14133837f427SRui Ueyama   if (ret == (unsigned)-1) {
14143837f427SRui Ueyama     setError("invalid program header type: " + tok);
14152ec34544SRui Ueyama     return PT_NULL;
14162ec34544SRui Ueyama   }
14173837f427SRui Ueyama   return ret;
14182ec34544SRui Ueyama }
14192ec34544SRui Ueyama 
14202ec34544SRui Ueyama // Reads an anonymous version declaration.
14212ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
14223837f427SRui Ueyama   std::vector<SymbolVersion> locals;
14233837f427SRui Ueyama   std::vector<SymbolVersion> globals;
14243837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
1425e28a70daSFangrui Song   for (const SymbolVersion &pat : locals)
1426e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
1427e28a70daSFangrui Song   for (const SymbolVersion &pat : globals)
1428e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(pat);
14292ec34544SRui Ueyama 
14302ec34544SRui Ueyama   expect(";");
14312ec34544SRui Ueyama }
14322ec34544SRui Ueyama 
14332ec34544SRui Ueyama // Reads a non-anonymous version definition,
14342ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
14353837f427SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef verStr) {
14362ec34544SRui Ueyama   // Read a symbol list.
14373837f427SRui Ueyama   std::vector<SymbolVersion> locals;
14383837f427SRui Ueyama   std::vector<SymbolVersion> globals;
14393837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
1440e28a70daSFangrui Song   for (const SymbolVersion &pat : locals)
1441e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
14422ec34544SRui Ueyama 
14432ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
14443837f427SRui Ueyama   VersionDefinition ver;
14453837f427SRui Ueyama   ver.name = verStr;
1446e28a70daSFangrui Song   ver.patterns = globals;
1447e28a70daSFangrui Song   ver.id = config->versionDefinitions.size();
14483837f427SRui Ueyama   config->versionDefinitions.push_back(ver);
14492ec34544SRui Ueyama 
14502ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
14512ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
14522ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
14532ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
14542ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
14555f380403SFangrui Song   if (next() != ";")
14562ec34544SRui Ueyama     expect(";");
14572ec34544SRui Ueyama }
14582ec34544SRui Ueyama 
14593837f427SRui Ueyama static bool hasWildcard(StringRef s) {
14603837f427SRui Ueyama   return s.find_first_of("?*[") != StringRef::npos;
14611e77ad14SRui Ueyama }
14621e77ad14SRui Ueyama 
14632ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
14642ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
14652ec34544SRui Ueyama ScriptParser::readSymbols() {
14663837f427SRui Ueyama   std::vector<SymbolVersion> locals;
14673837f427SRui Ueyama   std::vector<SymbolVersion> globals;
14683837f427SRui Ueyama   std::vector<SymbolVersion> *v = &globals;
14692ec34544SRui Ueyama 
1470b8a59c8aSBob Haarman   while (!errorCount()) {
14712ec34544SRui Ueyama     if (consume("}"))
14722ec34544SRui Ueyama       break;
14732ec34544SRui Ueyama     if (consumeLabel("local")) {
14743837f427SRui Ueyama       v = &locals;
14752ec34544SRui Ueyama       continue;
14762ec34544SRui Ueyama     }
14772ec34544SRui Ueyama     if (consumeLabel("global")) {
14783837f427SRui Ueyama       v = &globals;
14792ec34544SRui Ueyama       continue;
14802ec34544SRui Ueyama     }
14812ec34544SRui Ueyama 
14822ec34544SRui Ueyama     if (consume("extern")) {
14833837f427SRui Ueyama       std::vector<SymbolVersion> ext = readVersionExtern();
14843837f427SRui Ueyama       v->insert(v->end(), ext.begin(), ext.end());
14852ec34544SRui Ueyama     } else {
14863837f427SRui Ueyama       StringRef tok = next();
14873837f427SRui Ueyama       v->push_back({unquote(tok), false, hasWildcard(tok)});
14882ec34544SRui Ueyama     }
14892ec34544SRui Ueyama     expect(";");
14902ec34544SRui Ueyama   }
14913837f427SRui Ueyama   return {locals, globals};
14922ec34544SRui Ueyama }
14932ec34544SRui Ueyama 
14942ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
14952ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
149617324d8bSRui Ueyama //
149717324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
149817324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
14992ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
15003837f427SRui Ueyama   StringRef tok = next();
15013837f427SRui Ueyama   bool isCXX = tok == "\"C++\"";
15023837f427SRui Ueyama   if (!isCXX && tok != "\"C\"")
15032ec34544SRui Ueyama     setError("Unknown language");
15042ec34544SRui Ueyama   expect("{");
15052ec34544SRui Ueyama 
15063837f427SRui Ueyama   std::vector<SymbolVersion> ret;
1507b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
15083837f427SRui Ueyama     StringRef tok = next();
15093837f427SRui Ueyama     ret.push_back(
15103837f427SRui Ueyama         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
151117324d8bSRui Ueyama     if (consume("}"))
15123837f427SRui Ueyama       return ret;
15132ec34544SRui Ueyama     expect(";");
15142ec34544SRui Ueyama   }
15152ec34544SRui Ueyama 
15162ec34544SRui Ueyama   expect("}");
15173837f427SRui Ueyama   return ret;
15182ec34544SRui Ueyama }
15192ec34544SRui Ueyama 
152092b5b980SFangrui Song Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
15213837f427SRui Ueyama                                         StringRef s3) {
15223837f427SRui Ueyama   if (!consume(s1) && !consume(s2) && !consume(s3)) {
15233837f427SRui Ueyama     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
152492b5b980SFangrui Song     return [] { return 0; };
15252ec34544SRui Ueyama   }
15262ec34544SRui Ueyama   expect("=");
152792b5b980SFangrui Song   return readExpr();
15282ec34544SRui Ueyama }
15292ec34544SRui Ueyama 
15302ec34544SRui Ueyama // Parse the MEMORY command as specified in:
15312ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
15322ec34544SRui Ueyama //
15332ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
15342ec34544SRui Ueyama void ScriptParser::readMemory() {
15352ec34544SRui Ueyama   expect("{");
1536b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
15373837f427SRui Ueyama     StringRef tok = next();
15383837f427SRui Ueyama     if (tok == "INCLUDE") {
15392e9d40d5SRui Ueyama       readInclude();
15402e9d40d5SRui Ueyama       continue;
15412e9d40d5SRui Ueyama     }
15422ec34544SRui Ueyama 
15433837f427SRui Ueyama     uint32_t flags = 0;
15443837f427SRui Ueyama     uint32_t negFlags = 0;
15452ec34544SRui Ueyama     if (consume("(")) {
15463837f427SRui Ueyama       std::tie(flags, negFlags) = readMemoryAttributes();
15472ec34544SRui Ueyama       expect(")");
15482ec34544SRui Ueyama     }
15492ec34544SRui Ueyama     expect(":");
15502ec34544SRui Ueyama 
155192b5b980SFangrui Song     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
15522ec34544SRui Ueyama     expect(",");
155392b5b980SFangrui Song     Expr length = readMemoryAssignment("LENGTH", "len", "l");
15542ec34544SRui Ueyama 
15555f37541cSGeorge Rimar     // Add the memory region to the region map.
15563837f427SRui Ueyama     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, negFlags);
15573837f427SRui Ueyama     if (!script->memoryRegions.insert({tok, mr}).second)
15583837f427SRui Ueyama       setError("region '" + tok + "' already defined");
15592ec34544SRui Ueyama   }
15602ec34544SRui Ueyama }
15612ec34544SRui Ueyama 
15622ec34544SRui Ueyama // This function parses the attributes used to match against section
15632ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
15642ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
15652ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
15663837f427SRui Ueyama   uint32_t flags = 0;
15673837f427SRui Ueyama   uint32_t negFlags = 0;
15683837f427SRui Ueyama   bool invert = false;
15692ec34544SRui Ueyama 
15703837f427SRui Ueyama   for (char c : next().lower()) {
15713837f427SRui Ueyama     uint32_t flag = 0;
15723837f427SRui Ueyama     if (c == '!')
15733837f427SRui Ueyama       invert = !invert;
15743837f427SRui Ueyama     else if (c == 'w')
15753837f427SRui Ueyama       flag = SHF_WRITE;
15763837f427SRui Ueyama     else if (c == 'x')
15773837f427SRui Ueyama       flag = SHF_EXECINSTR;
15783837f427SRui Ueyama     else if (c == 'a')
15793837f427SRui Ueyama       flag = SHF_ALLOC;
15803837f427SRui Ueyama     else if (c != 'r')
15812ec34544SRui Ueyama       setError("invalid memory region attribute");
15822ec34544SRui Ueyama 
15833837f427SRui Ueyama     if (invert)
15843837f427SRui Ueyama       negFlags |= flag;
15852ec34544SRui Ueyama     else
15863837f427SRui Ueyama       flags |= flag;
15872ec34544SRui Ueyama   }
15883837f427SRui Ueyama   return {flags, negFlags};
15892ec34544SRui Ueyama }
15902ec34544SRui Ueyama 
1591bd8cfe65SFangrui Song void readLinkerScript(MemoryBufferRef mb) {
15923837f427SRui Ueyama   ScriptParser(mb).readLinkerScript();
15932ec34544SRui Ueyama }
15942ec34544SRui Ueyama 
1595bd8cfe65SFangrui Song void readVersionScript(MemoryBufferRef mb) {
15963837f427SRui Ueyama   ScriptParser(mb).readVersionScript();
15972ec34544SRui Ueyama }
15982ec34544SRui Ueyama 
1599bd8cfe65SFangrui Song void readDynamicList(MemoryBufferRef mb) { ScriptParser(mb).readDynamicList(); }
16008c7e8cceSPetr Hosek 
1601bd8cfe65SFangrui Song void readDefsym(StringRef name, MemoryBufferRef mb) {
16023837f427SRui Ueyama   ScriptParser(mb).readDefsym(name);
16038c7e8cceSPetr Hosek }
1604bd8cfe65SFangrui Song 
1605bd8cfe65SFangrui Song } // namespace elf
1606bd8cfe65SFangrui Song } // namespace lld
1607