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"
17*b01430a0SFangrui Song #include "InputFiles.h"
182ec34544SRui Ueyama #include "LinkerScript.h"
192ec34544SRui Ueyama #include "OutputSections.h"
202ec34544SRui Ueyama #include "ScriptLexer.h"
2127bb7990SFangrui Song #include "SymbolTable.h"
222ec34544SRui Ueyama #include "Symbols.h"
232ec34544SRui Ueyama #include "Target.h"
2483d59e05SAlexandre Ganea #include "lld/Common/CommonLinkerContext.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"
33fa1145a8SIsaac Richter #include "llvm/Support/MathExtras.h"
342ec34544SRui Ueyama #include "llvm/Support/Path.h"
35439341b9SJames Henderson #include "llvm/Support/TimeProfiler.h"
362ec34544SRui Ueyama #include <cassert>
372ec34544SRui Ueyama #include <limits>
382ec34544SRui Ueyama #include <vector>
392ec34544SRui Ueyama 
402ec34544SRui Ueyama using namespace llvm;
412ec34544SRui Ueyama using namespace llvm::ELF;
42b58079d4SRui Ueyama using namespace llvm::support::endian;
4307837b8fSFangrui Song using namespace lld;
4407837b8fSFangrui Song using namespace lld::elf;
452ec34544SRui Ueyama 
4696b3fe02SRui Ueyama namespace {
4796b3fe02SRui Ueyama class ScriptParser final : ScriptLexer {
482ec34544SRui Ueyama public:
493837f427SRui Ueyama   ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) {
5011ae59f0SRui Ueyama     // Initialize IsUnderSysroot
513837f427SRui Ueyama     if (config->sysroot == "")
5211ae59f0SRui Ueyama       return;
533837f427SRui Ueyama     StringRef path = mb.getBufferIdentifier();
543837f427SRui Ueyama     for (; !path.empty(); path = sys::path::parent_path(path)) {
553837f427SRui Ueyama       if (!sys::fs::equivalent(config->sysroot, path))
5611ae59f0SRui Ueyama         continue;
573837f427SRui Ueyama       isUnderSysroot = true;
5811ae59f0SRui Ueyama       return;
5911ae59f0SRui Ueyama     }
6011ae59f0SRui Ueyama   }
612ec34544SRui Ueyama 
622ec34544SRui Ueyama   void readLinkerScript();
632ec34544SRui Ueyama   void readVersionScript();
642ec34544SRui Ueyama   void readDynamicList();
653837f427SRui Ueyama   void readDefsym(StringRef name);
662ec34544SRui Ueyama 
672ec34544SRui Ueyama private:
683837f427SRui Ueyama   void addFile(StringRef path);
692ec34544SRui Ueyama 
702ec34544SRui Ueyama   void readAsNeeded();
712ec34544SRui Ueyama   void readEntry();
722ec34544SRui Ueyama   void readExtern();
732ec34544SRui Ueyama   void readGroup();
742ec34544SRui Ueyama   void readInclude();
751d92aa73SRui Ueyama   void readInput();
762ec34544SRui Ueyama   void readMemory();
772ec34544SRui Ueyama   void readOutput();
782ec34544SRui Ueyama   void readOutputArch();
792ec34544SRui Ueyama   void readOutputFormat();
80899fdf54SFangrui Song   void readOverwriteSections();
812ec34544SRui Ueyama   void readPhdrs();
825f37541cSGeorge Rimar   void readRegionAlias();
832ec34544SRui Ueyama   void readSearchDir();
842ec34544SRui Ueyama   void readSections();
85e262bb1aSRui Ueyama   void readTarget();
862ec34544SRui Ueyama   void readVersion();
872ec34544SRui Ueyama   void readVersionScriptCommand();
882ec34544SRui Ueyama 
893837f427SRui Ueyama   SymbolAssignment *readSymbolAssignment(StringRef name);
903837f427SRui Ueyama   ByteCommand *readByteCommand(StringRef tok);
91b0486051SSimon Atanasyan   std::array<uint8_t, 4> readFill();
923837f427SRui Ueyama   bool readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2);
933837f427SRui Ueyama   void readSectionAddressType(OutputSection *cmd);
94a582419aSGeorge Rimar   OutputSection *readOverlaySectionDescription();
953837f427SRui Ueyama   OutputSection *readOutputSectionDescription(StringRef outSec);
9664038ef8SFangrui Song   SmallVector<SectionCommand *, 0> readOverlay();
97a1c2ee01SFangrui Song   SmallVector<StringRef, 0> readOutputSectionPhdrs();
98dbd0ad33SPeter Smith   std::pair<uint64_t, uint64_t> readInputSectionFlags();
993837f427SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef tok);
1002ec34544SRui Ueyama   StringMatcher readFilePatterns();
10164038ef8SFangrui Song   SmallVector<SectionPattern, 0> readInputSectionsList();
102dbd0ad33SPeter Smith   InputSectionDescription *readInputSectionRules(StringRef filePattern,
103dbd0ad33SPeter Smith                                                  uint64_t withFlags,
104dbd0ad33SPeter Smith                                                  uint64_t withoutFlags);
1052ec34544SRui Ueyama   unsigned readPhdrType();
1062a9aed0eSFangrui Song   SortSectionPolicy peekSortKind();
1072ec34544SRui Ueyama   SortSectionPolicy readSortKind();
1083837f427SRui Ueyama   SymbolAssignment *readProvideHidden(bool provide, bool hidden);
1093837f427SRui Ueyama   SymbolAssignment *readAssignment(StringRef tok);
1102ec34544SRui Ueyama   void readSort();
111d30a78b3SGeorge Rimar   Expr readAssert();
1125fb17128SGeorge Rimar   Expr readConstant();
1135fb17128SGeorge Rimar   Expr getPageSize();
1142ec34544SRui Ueyama 
11592b5b980SFangrui Song   Expr readMemoryAssignment(StringRef, StringRef, StringRef);
1168cdf1c1eSIgor Kudrin   void readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
1178cdf1c1eSIgor Kudrin                             uint32_t &negFlags, uint32_t &negInvFlags);
1182ec34544SRui Ueyama 
1193837f427SRui Ueyama   Expr combine(StringRef op, Expr l, Expr r);
1202ec34544SRui Ueyama   Expr readExpr();
1213837f427SRui Ueyama   Expr readExpr1(Expr lhs, int minPrec);
1222ec34544SRui Ueyama   StringRef readParenLiteral();
1232ec34544SRui Ueyama   Expr readPrimary();
1243837f427SRui Ueyama   Expr readTernary(Expr cond);
1252ec34544SRui Ueyama   Expr readParenExpr();
1262ec34544SRui Ueyama 
1272ec34544SRui Ueyama   // For parsing version script.
12864038ef8SFangrui Song   SmallVector<SymbolVersion, 0> readVersionExtern();
1292ec34544SRui Ueyama   void readAnonymousDeclaration();
1303837f427SRui Ueyama   void readVersionDeclaration(StringRef verStr);
1312ec34544SRui Ueyama 
13264038ef8SFangrui Song   std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
1332ec34544SRui Ueyama   readSymbols();
1342ec34544SRui Ueyama 
135bf6e259bSFangrui Song   // True if a script being read is in the --sysroot directory.
1363837f427SRui Ueyama   bool isUnderSysroot = false;
1370440be4aSRui Ueyama 
1380440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1393837f427SRui Ueyama   StringSet<> seen;
1402ec34544SRui Ueyama };
14196b3fe02SRui Ueyama } // namespace
1422ec34544SRui Ueyama 
1433837f427SRui Ueyama static StringRef unquote(StringRef s) {
1443837f427SRui Ueyama   if (s.startswith("\""))
1453837f427SRui Ueyama     return s.substr(1, s.size() - 2);
1463837f427SRui Ueyama   return s;
1471e77ad14SRui Ueyama }
1481e77ad14SRui Ueyama 
1492ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1502ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1513837f427SRui Ueyama static void moveAbsRight(ExprValue &a, ExprValue &b) {
1523837f427SRui Ueyama   if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
1533837f427SRui Ueyama     std::swap(a, b);
1543837f427SRui Ueyama   if (!b.isAbsolute())
1553837f427SRui Ueyama     error(a.loc + ": at least one side of the expression must be absolute");
1562ec34544SRui Ueyama }
1572ec34544SRui Ueyama 
1583837f427SRui Ueyama static ExprValue add(ExprValue a, ExprValue b) {
1593837f427SRui Ueyama   moveAbsRight(a, b);
1603837f427SRui Ueyama   return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
1612ec34544SRui Ueyama }
1622ec34544SRui Ueyama 
1633837f427SRui Ueyama static ExprValue sub(ExprValue a, ExprValue b) {
16463a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1653837f427SRui Ueyama   if (!a.isAbsolute() && !b.isAbsolute())
1663837f427SRui Ueyama     return a.getValue() - b.getValue();
1673837f427SRui Ueyama   return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
1682ec34544SRui Ueyama }
1692ec34544SRui Ueyama 
1703837f427SRui Ueyama static ExprValue bitAnd(ExprValue a, ExprValue b) {
1713837f427SRui Ueyama   moveAbsRight(a, b);
1723837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1733837f427SRui Ueyama           (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
1742ec34544SRui Ueyama }
1752ec34544SRui Ueyama 
1763837f427SRui Ueyama static ExprValue bitOr(ExprValue a, ExprValue b) {
1773837f427SRui Ueyama   moveAbsRight(a, b);
1783837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1793837f427SRui Ueyama           (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
1802ec34544SRui Ueyama }
1812ec34544SRui Ueyama 
1822ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1832ec34544SRui Ueyama   expect("{");
18464038ef8SFangrui Song   SmallVector<SymbolVersion, 0> locals;
18564038ef8SFangrui Song   SmallVector<SymbolVersion, 0> globals;
1863837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
187d72d97b3SRafael Espindola   expect(";");
188d72d97b3SRafael Espindola 
189d72d97b3SRafael Espindola   if (!atEOF()) {
1902ec34544SRui Ueyama     setError("EOF expected, but got " + next());
191d72d97b3SRafael Espindola     return;
192d72d97b3SRafael Espindola   }
1933837f427SRui Ueyama   if (!locals.empty()) {
194d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
195d72d97b3SRafael Espindola     return;
196d72d97b3SRafael Espindola   }
197d72d97b3SRafael Espindola 
1983837f427SRui Ueyama   for (SymbolVersion v : globals)
1993837f427SRui Ueyama     config->dynamicList.push_back(v);
2002ec34544SRui Ueyama }
2012ec34544SRui Ueyama 
2022ec34544SRui Ueyama void ScriptParser::readVersionScript() {
2032ec34544SRui Ueyama   readVersionScriptCommand();
2042ec34544SRui Ueyama   if (!atEOF())
2052ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2062ec34544SRui Ueyama }
2072ec34544SRui Ueyama 
2082ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2092ec34544SRui Ueyama   if (consume("{")) {
2102ec34544SRui Ueyama     readAnonymousDeclaration();
2112ec34544SRui Ueyama     return;
2122ec34544SRui Ueyama   }
2132ec34544SRui Ueyama 
214b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2153837f427SRui Ueyama     StringRef verStr = next();
2163837f427SRui Ueyama     if (verStr == "{") {
2172ec34544SRui Ueyama       setError("anonymous version definition is used in "
2182ec34544SRui Ueyama                "combination with other version definitions");
2192ec34544SRui Ueyama       return;
2202ec34544SRui Ueyama     }
2212ec34544SRui Ueyama     expect("{");
2223837f427SRui Ueyama     readVersionDeclaration(verStr);
2232ec34544SRui Ueyama   }
2242ec34544SRui Ueyama }
2252ec34544SRui Ueyama 
2262ec34544SRui Ueyama void ScriptParser::readVersion() {
2272ec34544SRui Ueyama   expect("{");
2282ec34544SRui Ueyama   readVersionScriptCommand();
2292ec34544SRui Ueyama   expect("}");
2302ec34544SRui Ueyama }
2312ec34544SRui Ueyama 
2322ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2332ec34544SRui Ueyama   while (!atEOF()) {
2343837f427SRui Ueyama     StringRef tok = next();
2353837f427SRui Ueyama     if (tok == ";")
2362ec34544SRui Ueyama       continue;
2372ec34544SRui Ueyama 
2383837f427SRui Ueyama     if (tok == "ENTRY") {
2392ec34544SRui Ueyama       readEntry();
2403837f427SRui Ueyama     } else if (tok == "EXTERN") {
2412ec34544SRui Ueyama       readExtern();
2423837f427SRui Ueyama     } else if (tok == "GROUP") {
2432ec34544SRui Ueyama       readGroup();
2443837f427SRui Ueyama     } else if (tok == "INCLUDE") {
2452ec34544SRui Ueyama       readInclude();
2463837f427SRui Ueyama     } else if (tok == "INPUT") {
2471d92aa73SRui Ueyama       readInput();
2483837f427SRui Ueyama     } else if (tok == "MEMORY") {
2492ec34544SRui Ueyama       readMemory();
2503837f427SRui Ueyama     } else if (tok == "OUTPUT") {
2512ec34544SRui Ueyama       readOutput();
2523837f427SRui Ueyama     } else if (tok == "OUTPUT_ARCH") {
2532ec34544SRui Ueyama       readOutputArch();
2543837f427SRui Ueyama     } else if (tok == "OUTPUT_FORMAT") {
2552ec34544SRui Ueyama       readOutputFormat();
256899fdf54SFangrui Song     } else if (tok == "OVERWRITE_SECTIONS") {
257899fdf54SFangrui Song       readOverwriteSections();
2583837f427SRui Ueyama     } else if (tok == "PHDRS") {
2592ec34544SRui Ueyama       readPhdrs();
2603837f427SRui Ueyama     } else if (tok == "REGION_ALIAS") {
2615f37541cSGeorge Rimar       readRegionAlias();
2623837f427SRui Ueyama     } else if (tok == "SEARCH_DIR") {
2632ec34544SRui Ueyama       readSearchDir();
2643837f427SRui Ueyama     } else if (tok == "SECTIONS") {
2652ec34544SRui Ueyama       readSections();
2663837f427SRui Ueyama     } else if (tok == "TARGET") {
267e262bb1aSRui Ueyama       readTarget();
2683837f427SRui Ueyama     } else if (tok == "VERSION") {
2692ec34544SRui Ueyama       readVersion();
2703837f427SRui Ueyama     } else if (SymbolAssignment *cmd = readAssignment(tok)) {
2713837f427SRui Ueyama       script->sectionCommands.push_back(cmd);
2722ec34544SRui Ueyama     } else {
2733837f427SRui Ueyama       setError("unknown directive: " + tok);
2742ec34544SRui Ueyama     }
2752ec34544SRui Ueyama   }
2762ec34544SRui Ueyama }
2772ec34544SRui Ueyama 
2783837f427SRui Ueyama void ScriptParser::readDefsym(StringRef name) {
279c1522816SGeorge Rimar   if (errorCount())
280c1522816SGeorge Rimar     return;
2813837f427SRui Ueyama   Expr e = readExpr();
2828c7e8cceSPetr Hosek   if (!atEOF())
2838c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
2843837f427SRui Ueyama   SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation());
2853837f427SRui Ueyama   script->sectionCommands.push_back(cmd);
2868c7e8cceSPetr Hosek }
2878c7e8cceSPetr Hosek 
2883837f427SRui Ueyama void ScriptParser::addFile(StringRef s) {
2893837f427SRui Ueyama   if (isUnderSysroot && s.startswith("/")) {
2903837f427SRui Ueyama     SmallString<128> pathData;
2913837f427SRui Ueyama     StringRef path = (config->sysroot + s).toStringRef(pathData);
2922508733eSFangrui Song     if (sys::fs::exists(path))
29383d59e05SAlexandre Ganea       driver->addFile(saver().save(path), /*withLOption=*/false);
2942508733eSFangrui Song     else
2952508733eSFangrui Song       setError("cannot find " + s + " inside " + config->sysroot);
2962ec34544SRui Ueyama     return;
2972ec34544SRui Ueyama   }
2982ec34544SRui Ueyama 
2993837f427SRui Ueyama   if (s.startswith("/")) {
300c384ca3cSFangrui Song     // Case 1: s is an absolute path. Just open it.
30149a3ad21SRui Ueyama     driver->addFile(s, /*withLOption=*/false);
3023837f427SRui Ueyama   } else if (s.startswith("=")) {
303c384ca3cSFangrui Song     // Case 2: relative to the sysroot.
3043837f427SRui Ueyama     if (config->sysroot.empty())
30549a3ad21SRui Ueyama       driver->addFile(s.substr(1), /*withLOption=*/false);
3062ec34544SRui Ueyama     else
30783d59e05SAlexandre Ganea       driver->addFile(saver().save(config->sysroot + "/" + s.substr(1)),
30849a3ad21SRui Ueyama                       /*withLOption=*/false);
3093837f427SRui Ueyama   } else if (s.startswith("-l")) {
310c384ca3cSFangrui Song     // Case 3: search in the list of library paths.
3113837f427SRui Ueyama     driver->addLibrary(s.substr(2));
312c384ca3cSFangrui Song   } else {
313c384ca3cSFangrui Song     // Case 4: s is a relative path. Search in the directory of the script file.
314c384ca3cSFangrui Song     std::string filename = std::string(getCurrentMB().getBufferIdentifier());
315c384ca3cSFangrui Song     StringRef directory = sys::path::parent_path(filename);
316c384ca3cSFangrui Song     if (!directory.empty()) {
317c384ca3cSFangrui Song       SmallString<0> path(directory);
318c384ca3cSFangrui Song       sys::path::append(path, s);
319c384ca3cSFangrui Song       if (sys::fs::exists(path)) {
320c384ca3cSFangrui Song         driver->addFile(path, /*withLOption=*/false);
321c384ca3cSFangrui Song         return;
322c384ca3cSFangrui Song       }
323c384ca3cSFangrui Song     }
324c384ca3cSFangrui Song     // Then search in the current working directory.
325c384ca3cSFangrui Song     if (sys::fs::exists(s)) {
32649a3ad21SRui Ueyama       driver->addFile(s, /*withLOption=*/false);
3272ec34544SRui Ueyama     } else {
328c384ca3cSFangrui Song       // Finally, search in the list of library paths.
3293837f427SRui Ueyama       if (Optional<std::string> path = findFromSearchPaths(s))
33083d59e05SAlexandre Ganea         driver->addFile(saver().save(*path), /*withLOption=*/true);
3312ec34544SRui Ueyama       else
3323837f427SRui Ueyama         setError("unable to find " + s);
3332ec34544SRui Ueyama     }
3342ec34544SRui Ueyama   }
335c384ca3cSFangrui Song }
3362ec34544SRui Ueyama 
3372ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3382ec34544SRui Ueyama   expect("(");
3393837f427SRui Ueyama   bool orig = config->asNeeded;
3403837f427SRui Ueyama   config->asNeeded = true;
341b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3422ec34544SRui Ueyama     addFile(unquote(next()));
3433837f427SRui Ueyama   config->asNeeded = orig;
3442ec34544SRui Ueyama }
3452ec34544SRui Ueyama 
3462ec34544SRui Ueyama void ScriptParser::readEntry() {
3472ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3482ec34544SRui Ueyama   expect("(");
3493837f427SRui Ueyama   StringRef tok = next();
3503837f427SRui Ueyama   if (config->entry.empty())
3513837f427SRui Ueyama     config->entry = tok;
3522ec34544SRui Ueyama   expect(")");
3532ec34544SRui Ueyama }
3542ec34544SRui Ueyama 
3552ec34544SRui Ueyama void ScriptParser::readExtern() {
3562ec34544SRui Ueyama   expect("(");
357b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3583837f427SRui Ueyama     config->undefined.push_back(unquote(next()));
3592ec34544SRui Ueyama }
3602ec34544SRui Ueyama 
3612ec34544SRui Ueyama void ScriptParser::readGroup() {
3623837f427SRui Ueyama   bool orig = InputFile::isInGroup;
3633837f427SRui Ueyama   InputFile::isInGroup = true;
3641d92aa73SRui Ueyama   readInput();
3653837f427SRui Ueyama   InputFile::isInGroup = orig;
3663837f427SRui Ueyama   if (!orig)
3673837f427SRui Ueyama     ++InputFile::nextGroupId;
3682ec34544SRui Ueyama }
3692ec34544SRui Ueyama 
3702ec34544SRui Ueyama void ScriptParser::readInclude() {
3713837f427SRui Ueyama   StringRef tok = unquote(next());
3722ec34544SRui Ueyama 
3733837f427SRui Ueyama   if (!seen.insert(tok).second) {
3740440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3750440be4aSRui Ueyama     return;
3760440be4aSRui Ueyama   }
3770440be4aSRui Ueyama 
3783837f427SRui Ueyama   if (Optional<std::string> path = searchScript(tok)) {
3793837f427SRui Ueyama     if (Optional<MemoryBufferRef> mb = readFile(*path))
3803837f427SRui Ueyama       tokenize(*mb);
3812ec34544SRui Ueyama     return;
3822ec34544SRui Ueyama   }
3833837f427SRui Ueyama   setError("cannot find linker script " + tok);
3842ec34544SRui Ueyama }
3852ec34544SRui Ueyama 
3861d92aa73SRui Ueyama void ScriptParser::readInput() {
3871d92aa73SRui Ueyama   expect("(");
3881d92aa73SRui Ueyama   while (!errorCount() && !consume(")")) {
3891d92aa73SRui Ueyama     if (consume("AS_NEEDED"))
3901d92aa73SRui Ueyama       readAsNeeded();
3911d92aa73SRui Ueyama     else
3921d92aa73SRui Ueyama       addFile(unquote(next()));
3931d92aa73SRui Ueyama   }
3941d92aa73SRui Ueyama }
3951d92aa73SRui Ueyama 
3962ec34544SRui Ueyama void ScriptParser::readOutput() {
3972ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3982ec34544SRui Ueyama   expect("(");
3993837f427SRui Ueyama   StringRef tok = next();
4003837f427SRui Ueyama   if (config->outputFile.empty())
4013837f427SRui Ueyama     config->outputFile = unquote(tok);
4022ec34544SRui Ueyama   expect(")");
4032ec34544SRui Ueyama }
4042ec34544SRui Ueyama 
4052ec34544SRui Ueyama void ScriptParser::readOutputArch() {
4062ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
4072ec34544SRui Ueyama   expect("(");
408b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4092ec34544SRui Ueyama     skip();
4102ec34544SRui Ueyama }
4112ec34544SRui Ueyama 
4123837f427SRui Ueyama static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
4133837f427SRui Ueyama   return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
4144f8c8228SRui Ueyama       .Case("elf32-i386", {ELF32LEKind, EM_386})
4154f8c8228SRui Ueyama       .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
4164f8c8228SRui Ueyama       .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
4174f8c8228SRui Ueyama       .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
41819b134ccSDimitry Andric       .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
4194f8c8228SRui Ueyama       .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
4207605a9a0SFangrui Song       .Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64})
4214134143cSRui Ueyama       .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
422275eb828SBrandon Bergren       .Case("elf32-powerpcle", {ELF32LEKind, EM_PPC})
4234f8c8228SRui Ueyama       .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
4244f8c8228SRui Ueyama       .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
4254f8c8228SRui Ueyama       .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
4264134143cSRui Ueyama       .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
4274f8c8228SRui Ueyama       .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
4284f8c8228SRui Ueyama       .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
4294f8c8228SRui Ueyama       .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
4304f8c8228SRui Ueyama       .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
4314f8c8228SRui Ueyama       .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
43244d908d7SFangrui Song       .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})
43344d908d7SFangrui Song       .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})
434aff950e9SLemonBoy       .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9})
43592c6141cSLemonBoy       .Case("elf32-msp430", {ELF32LEKind, EM_MSP430})
4364f8c8228SRui Ueyama       .Default({ELFNoneKind, EM_NONE});
437ea8cd00aSRui Ueyama }
438ea8cd00aSRui Ueyama 
439eea34aaeSFangrui Song // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
440eea34aaeSFangrui Song // big if -EB is specified, little if -EL is specified, or default if neither is
441eea34aaeSFangrui Song // specified.
4422ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
4432ec34544SRui Ueyama   expect("(");
444ea8cd00aSRui Ueyama 
445eea34aaeSFangrui Song   StringRef s;
4462822852fSShoaib Meenai   config->bfdname = unquote(next());
447eea34aaeSFangrui Song   if (!consume(")")) {
448eea34aaeSFangrui Song     expect(",");
449eea34aaeSFangrui Song     s = unquote(next());
450eea34aaeSFangrui Song     if (config->optEB)
451eea34aaeSFangrui Song       config->bfdname = s;
452eea34aaeSFangrui Song     expect(",");
453eea34aaeSFangrui Song     s = unquote(next());
454eea34aaeSFangrui Song     if (config->optEL)
455eea34aaeSFangrui Song       config->bfdname = s;
456eea34aaeSFangrui Song     consume(")");
457eea34aaeSFangrui Song   }
458eea34aaeSFangrui Song   s = config->bfdname;
4593837f427SRui Ueyama   if (s.consume_back("-freebsd"))
4603837f427SRui Ueyama     config->osabi = ELFOSABI_FREEBSD;
4614f8c8228SRui Ueyama 
4623837f427SRui Ueyama   std::tie(config->ekind, config->emachine) = parseBfdName(s);
4633837f427SRui Ueyama   if (config->emachine == EM_NONE)
4642822852fSShoaib Meenai     setError("unknown output format name: " + config->bfdname);
4653837f427SRui Ueyama   if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
4663837f427SRui Ueyama     config->mipsN32Abi = true;
46792c6141cSLemonBoy   if (config->emachine == EM_MSP430)
46892c6141cSLemonBoy     config->osabi = ELFOSABI_STANDALONE;
4692ec34544SRui Ueyama }
4702ec34544SRui Ueyama 
4712ec34544SRui Ueyama void ScriptParser::readPhdrs() {
4722ec34544SRui Ueyama   expect("{");
4732ec34544SRui Ueyama 
474b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4753837f427SRui Ueyama     PhdrsCommand cmd;
4763837f427SRui Ueyama     cmd.name = next();
4773837f427SRui Ueyama     cmd.type = readPhdrType();
478b579c439SRui Ueyama 
479b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
480b579c439SRui Ueyama       if (consume("FILEHDR"))
4813837f427SRui Ueyama         cmd.hasFilehdr = true;
482b579c439SRui Ueyama       else if (consume("PHDRS"))
4833837f427SRui Ueyama         cmd.hasPhdrs = true;
484b579c439SRui Ueyama       else if (consume("AT"))
4853837f427SRui Ueyama         cmd.lmaExpr = readParenExpr();
486b579c439SRui Ueyama       else if (consume("FLAGS"))
4873837f427SRui Ueyama         cmd.flags = readParenExpr()().getValue();
488b579c439SRui Ueyama       else
489b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
490b579c439SRui Ueyama     }
4910ae2c24cSRui Ueyama 
4923837f427SRui Ueyama     script->phdrsCommands.push_back(cmd);
4932ec34544SRui Ueyama   }
4942ec34544SRui Ueyama }
4952ec34544SRui Ueyama 
4965f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4975f37541cSGeorge Rimar   expect("(");
4983837f427SRui Ueyama   StringRef alias = unquote(next());
4995f37541cSGeorge Rimar   expect(",");
5003837f427SRui Ueyama   StringRef name = next();
5015f37541cSGeorge Rimar   expect(")");
5025f37541cSGeorge Rimar 
5033837f427SRui Ueyama   if (script->memoryRegions.count(alias))
5043837f427SRui Ueyama     setError("redefinition of memory region '" + alias + "'");
5053837f427SRui Ueyama   if (!script->memoryRegions.count(name))
5063837f427SRui Ueyama     setError("memory region '" + name + "' is not defined");
5073837f427SRui Ueyama   script->memoryRegions.insert({alias, script->memoryRegions[name]});
5085f37541cSGeorge Rimar }
5095f37541cSGeorge Rimar 
5102ec34544SRui Ueyama void ScriptParser::readSearchDir() {
5112ec34544SRui Ueyama   expect("(");
5123837f427SRui Ueyama   StringRef tok = next();
5133837f427SRui Ueyama   if (!config->nostdlib)
5143837f427SRui Ueyama     config->searchPaths.push_back(unquote(tok));
5152ec34544SRui Ueyama   expect(")");
5162ec34544SRui Ueyama }
5172ec34544SRui Ueyama 
518a582419aSGeorge Rimar // This reads an overlay description. Overlays are used to describe output
519a582419aSGeorge Rimar // sections that use the same virtual memory range and normally would trigger
520a582419aSGeorge Rimar // linker's sections sanity check failures.
521a582419aSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
52264038ef8SFangrui Song SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() {
523a582419aSGeorge Rimar   // VA and LMA expressions are optional, though for simplicity of
524a582419aSGeorge Rimar   // implementation we assume they are not. That is what OVERLAY was designed
525a582419aSGeorge Rimar   // for first of all: to allow sections with overlapping VAs at different LMAs.
5263837f427SRui Ueyama   Expr addrExpr = readExpr();
527a582419aSGeorge Rimar   expect(":");
528a582419aSGeorge Rimar   expect("AT");
5293837f427SRui Ueyama   Expr lmaExpr = readParenExpr();
530a582419aSGeorge Rimar   expect("{");
531a582419aSGeorge Rimar 
53264038ef8SFangrui Song   SmallVector<SectionCommand *, 0> v;
5333837f427SRui Ueyama   OutputSection *prev = nullptr;
534a582419aSGeorge Rimar   while (!errorCount() && !consume("}")) {
535a582419aSGeorge Rimar     // VA is the same for all sections. The LMAs are consecutive in memory
536a582419aSGeorge Rimar     // starting from the base load address specified.
5373837f427SRui Ueyama     OutputSection *os = readOverlaySectionDescription();
5383837f427SRui Ueyama     os->addrExpr = addrExpr;
5393837f427SRui Ueyama     if (prev)
5403837f427SRui Ueyama       os->lmaExpr = [=] { return prev->getLMA() + prev->size; };
541a582419aSGeorge Rimar     else
5423837f427SRui Ueyama       os->lmaExpr = lmaExpr;
5433837f427SRui Ueyama     v.push_back(os);
5443837f427SRui Ueyama     prev = os;
545a582419aSGeorge Rimar   }
546a582419aSGeorge Rimar 
547a582419aSGeorge Rimar   // According to the specification, at the end of the overlay, the location
548a582419aSGeorge Rimar   // counter should be equal to the overlay base address plus size of the
549a582419aSGeorge Rimar   // largest section seen in the overlay.
550a582419aSGeorge Rimar   // Here we want to create the Dot assignment command to achieve that.
5513837f427SRui Ueyama   Expr moveDot = [=] {
5523837f427SRui Ueyama     uint64_t max = 0;
5537051aeefSFangrui Song     for (SectionCommand *cmd : v)
5543837f427SRui Ueyama       max = std::max(max, cast<OutputSection>(cmd)->size);
5553837f427SRui Ueyama     return addrExpr().getValue() + max;
556a582419aSGeorge Rimar   };
5573837f427SRui Ueyama   v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation()));
5583837f427SRui Ueyama   return v;
559a582419aSGeorge Rimar }
560a582419aSGeorge Rimar 
561899fdf54SFangrui Song void ScriptParser::readOverwriteSections() {
562899fdf54SFangrui Song   expect("{");
563899fdf54SFangrui Song   while (!errorCount() && !consume("}"))
564899fdf54SFangrui Song     script->overwriteSections.push_back(readOutputSectionDescription(next()));
565899fdf54SFangrui Song }
566899fdf54SFangrui Song 
5672ec34544SRui Ueyama void ScriptParser::readSections() {
5682ec34544SRui Ueyama   expect("{");
56964038ef8SFangrui Song   SmallVector<SectionCommand *, 0> v;
570b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
5713837f427SRui Ueyama     StringRef tok = next();
5723837f427SRui Ueyama     if (tok == "OVERLAY") {
5737051aeefSFangrui Song       for (SectionCommand *cmd : readOverlay())
5743837f427SRui Ueyama         v.push_back(cmd);
575a582419aSGeorge Rimar       continue;
5763837f427SRui Ueyama     } else if (tok == "INCLUDE") {
5772e9d40d5SRui Ueyama       readInclude();
5782e9d40d5SRui Ueyama       continue;
579a582419aSGeorge Rimar     }
580a582419aSGeorge Rimar 
5817051aeefSFangrui Song     if (SectionCommand *cmd = readAssignment(tok))
5823837f427SRui Ueyama       v.push_back(cmd);
583d30a78b3SGeorge Rimar     else
5843837f427SRui Ueyama       v.push_back(readOutputSectionDescription(tok));
5852ec34544SRui Ueyama   }
5867c426fb1SFangrui Song   script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),
5877c426fb1SFangrui Song                                  v.end());
5889e2c8a9dSGeorge Rimar 
5897c426fb1SFangrui Song   if (atEOF() || !consume("INSERT")) {
5907c426fb1SFangrui Song     script->hasSectionsCommand = true;
5919e2c8a9dSGeorge Rimar     return;
5929e2c8a9dSGeorge Rimar   }
5939e2c8a9dSGeorge Rimar 
5947c426fb1SFangrui Song   bool isAfter = false;
5957c426fb1SFangrui Song   if (consume("AFTER"))
5967c426fb1SFangrui Song     isAfter = true;
5977c426fb1SFangrui Song   else if (!consume("BEFORE"))
5987c426fb1SFangrui Song     setError("expected AFTER/BEFORE, but got '" + next() + "'");
5997c426fb1SFangrui Song   StringRef where = next();
600a1c2ee01SFangrui Song   SmallVector<StringRef, 0> names;
6017051aeefSFangrui Song   for (SectionCommand *cmd : v)
6027c426fb1SFangrui Song     if (auto *os = dyn_cast<OutputSection>(cmd))
60303051f7aSFangrui Song       names.push_back(os->name);
60403051f7aSFangrui Song   if (!names.empty())
60503051f7aSFangrui Song     script->insertCommands.push_back({std::move(names), isAfter, where});
6062ec34544SRui Ueyama }
6072ec34544SRui Ueyama 
608e262bb1aSRui Ueyama void ScriptParser::readTarget() {
609e262bb1aSRui Ueyama   // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
610e262bb1aSRui Ueyama   // we accept only a limited set of BFD names (i.e. "elf" or "binary")
611e262bb1aSRui Ueyama   // for --format. We recognize only /^elf/ and "binary" in the linker
612e262bb1aSRui Ueyama   // script as well.
613e262bb1aSRui Ueyama   expect("(");
6143837f427SRui Ueyama   StringRef tok = next();
615e262bb1aSRui Ueyama   expect(")");
616e262bb1aSRui Ueyama 
6173837f427SRui Ueyama   if (tok.startswith("elf"))
6183837f427SRui Ueyama     config->formatBinary = false;
6193837f427SRui Ueyama   else if (tok == "binary")
6203837f427SRui Ueyama     config->formatBinary = true;
621e262bb1aSRui Ueyama   else
6223837f427SRui Ueyama     setError("unknown target: " + tok);
623e262bb1aSRui Ueyama }
624e262bb1aSRui Ueyama 
6253837f427SRui Ueyama static int precedence(StringRef op) {
6263837f427SRui Ueyama   return StringSwitch<int>(op)
627a5005482SGeorge Rimar       .Cases("*", "/", "%", 8)
628a5005482SGeorge Rimar       .Cases("+", "-", 7)
629a5005482SGeorge Rimar       .Cases("<<", ">>", 6)
630a5005482SGeorge Rimar       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
631a5005482SGeorge Rimar       .Case("&", 4)
632a5005482SGeorge Rimar       .Case("|", 3)
633a5005482SGeorge Rimar       .Case("&&", 2)
634a5005482SGeorge Rimar       .Case("||", 1)
6352ec34544SRui Ueyama       .Default(-1);
6362ec34544SRui Ueyama }
6372ec34544SRui Ueyama 
6382ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
639c42fe247SThomas Preud'homme   StringMatcher Matcher;
640c42fe247SThomas Preud'homme 
641b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
642c42fe247SThomas Preud'homme     Matcher.addPattern(SingleStringMatcher(next()));
643c42fe247SThomas Preud'homme   return Matcher;
6442ec34544SRui Ueyama }
6452ec34544SRui Ueyama 
6462a9aed0eSFangrui Song SortSectionPolicy ScriptParser::peekSortKind() {
6472a9aed0eSFangrui Song   return StringSwitch<SortSectionPolicy>(peek())
6482a9aed0eSFangrui Song       .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)
6492a9aed0eSFangrui Song       .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)
6502a9aed0eSFangrui Song       .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)
6512a9aed0eSFangrui Song       .Case("SORT_NONE", SortSectionPolicy::None)
6522a9aed0eSFangrui Song       .Default(SortSectionPolicy::Default);
6532a9aed0eSFangrui Song }
6542a9aed0eSFangrui Song 
6552ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
6562a9aed0eSFangrui Song   SortSectionPolicy ret = peekSortKind();
6572a9aed0eSFangrui Song   if (ret != SortSectionPolicy::Default)
6582a9aed0eSFangrui Song     skip();
6592a9aed0eSFangrui Song   return ret;
6602ec34544SRui Ueyama }
6612ec34544SRui Ueyama 
66203fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
66303fc8d1eSRui Ueyama //
66403fc8d1eSRui Ueyama // <contents> ::= <elem>*
66503fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
66603fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
66703fc8d1eSRui Ueyama //
66803fc8d1eSRui Ueyama // For example,
66903fc8d1eSRui Ueyama //
67003fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
67103fc8d1eSRui Ueyama //
67203fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
67303fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
67403fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
67564038ef8SFangrui Song SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() {
67664038ef8SFangrui Song   SmallVector<SectionPattern, 0> ret;
677b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
6783837f427SRui Ueyama     StringMatcher excludeFilePat;
6792ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
6802ec34544SRui Ueyama       expect("(");
6813837f427SRui Ueyama       excludeFilePat = readFilePatterns();
6822ec34544SRui Ueyama     }
6832ec34544SRui Ueyama 
684c42fe247SThomas Preud'homme     StringMatcher SectionMatcher;
6852a9aed0eSFangrui Song     // Break if the next token is ), EXCLUDE_FILE, or SORT*.
6862a9aed0eSFangrui Song     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" &&
6872a9aed0eSFangrui Song            peekSortKind() == SortSectionPolicy::Default)
688c42fe247SThomas Preud'homme       SectionMatcher.addPattern(unquote(next()));
6892ec34544SRui Ueyama 
690c42fe247SThomas Preud'homme     if (!SectionMatcher.empty())
691c42fe247SThomas Preud'homme       ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
6922a9aed0eSFangrui Song     else if (excludeFilePat.empty())
6932a9aed0eSFangrui Song       break;
6942ec34544SRui Ueyama     else
6952ec34544SRui Ueyama       setError("section pattern is expected");
6962ec34544SRui Ueyama   }
6973837f427SRui Ueyama   return ret;
6982ec34544SRui Ueyama }
6992ec34544SRui Ueyama 
7002ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
7012ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
7022ec34544SRui Ueyama //
7032ec34544SRui Ueyama // <patterns> ::= <section-list>
7042ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
7052ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
7062ec34544SRui Ueyama //
7072ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
7082ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
7092ec34544SRui Ueyama //
7102ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
7112ec34544SRui Ueyama InputSectionDescription *
712dbd0ad33SPeter Smith ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
713dbd0ad33SPeter Smith                                     uint64_t withoutFlags) {
714dbd0ad33SPeter Smith   auto *cmd =
715dbd0ad33SPeter Smith       make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
7162ec34544SRui Ueyama   expect("(");
7172ec34544SRui Ueyama 
718b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
7193837f427SRui Ueyama     SortSectionPolicy outer = readSortKind();
7203837f427SRui Ueyama     SortSectionPolicy inner = SortSectionPolicy::Default;
72164038ef8SFangrui Song     SmallVector<SectionPattern, 0> v;
7223837f427SRui Ueyama     if (outer != SortSectionPolicy::Default) {
7232ec34544SRui Ueyama       expect("(");
7243837f427SRui Ueyama       inner = readSortKind();
7253837f427SRui Ueyama       if (inner != SortSectionPolicy::Default) {
7262ec34544SRui Ueyama         expect("(");
7273837f427SRui Ueyama         v = readInputSectionsList();
7282ec34544SRui Ueyama         expect(")");
7292ec34544SRui Ueyama       } else {
7303837f427SRui Ueyama         v = readInputSectionsList();
7312ec34544SRui Ueyama       }
7322ec34544SRui Ueyama       expect(")");
7332ec34544SRui Ueyama     } else {
7343837f427SRui Ueyama       v = readInputSectionsList();
7352ec34544SRui Ueyama     }
7362ec34544SRui Ueyama 
7373837f427SRui Ueyama     for (SectionPattern &pat : v) {
7383837f427SRui Ueyama       pat.sortInner = inner;
7393837f427SRui Ueyama       pat.sortOuter = outer;
7402ec34544SRui Ueyama     }
7412ec34544SRui Ueyama 
7423837f427SRui Ueyama     std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
7432ec34544SRui Ueyama   }
7443837f427SRui Ueyama   return cmd;
7452ec34544SRui Ueyama }
7462ec34544SRui Ueyama 
7472ec34544SRui Ueyama InputSectionDescription *
7483837f427SRui Ueyama ScriptParser::readInputSectionDescription(StringRef tok) {
7492ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
7502ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
751dbd0ad33SPeter Smith   uint64_t withFlags = 0;
752dbd0ad33SPeter Smith   uint64_t withoutFlags = 0;
7533837f427SRui Ueyama   if (tok == "KEEP") {
7542ec34544SRui Ueyama     expect("(");
755dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
756dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
757dbd0ad33SPeter Smith     InputSectionDescription *cmd =
758dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags);
7592ec34544SRui Ueyama     expect(")");
7603837f427SRui Ueyama     script->keptSections.push_back(cmd);
7613837f427SRui Ueyama     return cmd;
7622ec34544SRui Ueyama   }
763dbd0ad33SPeter Smith   if (tok == "INPUT_SECTION_FLAGS") {
764dbd0ad33SPeter Smith     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
765dbd0ad33SPeter Smith     tok = next();
766dbd0ad33SPeter Smith   }
767dbd0ad33SPeter Smith   return readInputSectionRules(tok, withFlags, withoutFlags);
7682ec34544SRui Ueyama }
7692ec34544SRui Ueyama 
7702ec34544SRui Ueyama void ScriptParser::readSort() {
7712ec34544SRui Ueyama   expect("(");
7722ec34544SRui Ueyama   expect("CONSTRUCTORS");
7732ec34544SRui Ueyama   expect(")");
7742ec34544SRui Ueyama }
7752ec34544SRui Ueyama 
776d30a78b3SGeorge Rimar Expr ScriptParser::readAssert() {
7772ec34544SRui Ueyama   expect("(");
7783837f427SRui Ueyama   Expr e = readExpr();
7792ec34544SRui Ueyama   expect(",");
7803837f427SRui Ueyama   StringRef msg = unquote(next());
7812ec34544SRui Ueyama   expect(")");
782b579c439SRui Ueyama 
7832ec34544SRui Ueyama   return [=] {
7843837f427SRui Ueyama     if (!e().getValue())
7852682bc3cSFangrui Song       errorOrWarn(msg);
7863837f427SRui Ueyama     return script->getDot();
7872ec34544SRui Ueyama   };
7882ec34544SRui Ueyama }
7892ec34544SRui Ueyama 
79066f8ac8dSFangrui Song #define ECase(X)                                                               \
79166f8ac8dSFangrui Song   { #X, X }
79266f8ac8dSFangrui Song constexpr std::pair<const char *, unsigned> typeMap[] = {
79366f8ac8dSFangrui Song     ECase(SHT_PROGBITS),   ECase(SHT_NOTE),       ECase(SHT_NOBITS),
79466f8ac8dSFangrui Song     ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY),
79566f8ac8dSFangrui Song };
79666f8ac8dSFangrui Song #undef ECase
79766f8ac8dSFangrui Song 
798a46d08ebSGeorge Rimar // Tries to read the special directive for an output section definition which
79966f8ac8dSFangrui Song // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
80066f8ac8dSFangrui Song // "(TYPE=<value>)".
80166f8ac8dSFangrui Song // Tok1 and Tok2 are next 2 tokens peeked. See comment for
80266f8ac8dSFangrui Song // readSectionAddressType below.
8033837f427SRui Ueyama bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) {
8043837f427SRui Ueyama   if (tok1 != "(")
805a46d08ebSGeorge Rimar     return false;
80666f8ac8dSFangrui Song   if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" &&
80766f8ac8dSFangrui Song       tok2 != "OVERLAY" && tok2 != "TYPE")
808a46d08ebSGeorge Rimar     return false;
809a46d08ebSGeorge Rimar 
810a46d08ebSGeorge Rimar   expect("(");
811a46d08ebSGeorge Rimar   if (consume("NOLOAD")) {
812fdc41aa2SMatt Schulte     cmd->type = SHT_NOBITS;
81366f8ac8dSFangrui Song     cmd->typeIsSet = true;
81466f8ac8dSFangrui Song   } else if (consume("TYPE")) {
81566f8ac8dSFangrui Song     expect("=");
81666f8ac8dSFangrui Song     StringRef value = peek();
81766f8ac8dSFangrui Song     auto it = llvm::find_if(typeMap, [=](auto e) { return e.first == value; });
81866f8ac8dSFangrui Song     if (it != std::end(typeMap)) {
81966f8ac8dSFangrui Song       // The value is a recognized literal SHT_*.
82066f8ac8dSFangrui Song       cmd->type = it->second;
82166f8ac8dSFangrui Song       skip();
82266f8ac8dSFangrui Song     } else if (value.startswith("SHT_")) {
82366f8ac8dSFangrui Song       setError("unknown section type " + value);
82466f8ac8dSFangrui Song     } else {
82566f8ac8dSFangrui Song       // Otherwise, read an expression.
82666f8ac8dSFangrui Song       cmd->type = readExpr()().getValue();
82766f8ac8dSFangrui Song     }
82866f8ac8dSFangrui Song     cmd->typeIsSet = true;
829a46d08ebSGeorge Rimar   } else {
830a46d08ebSGeorge Rimar     skip(); // This is "COPY", "INFO" or "OVERLAY".
8313837f427SRui Ueyama     cmd->nonAlloc = true;
832a46d08ebSGeorge Rimar   }
833a46d08ebSGeorge Rimar   expect(")");
834a46d08ebSGeorge Rimar   return true;
835a46d08ebSGeorge Rimar }
836a46d08ebSGeorge Rimar 
8371c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
8381c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
8391c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
8403271d370SRui Ueyama //
8413271d370SRui Ueyama // An output section name can be followed by an address expression
8421c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
84397f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
8441c08e9f5SGeorge Rimar // of directive.
8453271d370SRui Ueyama //
846b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
847fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
8483837f427SRui Ueyama void ScriptParser::readSectionAddressType(OutputSection *cmd) {
84966f8ac8dSFangrui Song   // Temporarily set inExpr to support TYPE=<value> without spaces.
85066f8ac8dSFangrui Song   bool saved = std::exchange(inExpr, true);
85166f8ac8dSFangrui Song   bool isDirective = readSectionDirective(cmd, peek(), peek2());
85266f8ac8dSFangrui Song   inExpr = saved;
85366f8ac8dSFangrui Song   if (isDirective)
8543271d370SRui Ueyama     return;
8553271d370SRui Ueyama 
8563837f427SRui Ueyama   cmd->addrExpr = readExpr();
8573837f427SRui Ueyama   if (peek() == "(" && !readSectionDirective(cmd, "(", peek2()))
858a46d08ebSGeorge Rimar     setError("unknown section directive: " + peek2());
859fbb0463fSGeorge Rimar }
860fbb0463fSGeorge Rimar 
8613837f427SRui Ueyama static Expr checkAlignment(Expr e, std::string &loc) {
862f22ec9ddSGeorge Rimar   return [=] {
8633837f427SRui Ueyama     uint64_t alignment = std::max((uint64_t)1, e().getValue());
8643837f427SRui Ueyama     if (!isPowerOf2_64(alignment)) {
8653837f427SRui Ueyama       error(loc + ": alignment must be power of 2");
866f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
867f22ec9ddSGeorge Rimar     }
8683837f427SRui Ueyama     return alignment;
869f22ec9ddSGeorge Rimar   };
870f22ec9ddSGeorge Rimar }
871f22ec9ddSGeorge Rimar 
872a582419aSGeorge Rimar OutputSection *ScriptParser::readOverlaySectionDescription() {
8733837f427SRui Ueyama   OutputSection *cmd =
8743837f427SRui Ueyama       script->createOutputSection(next(), getCurrentLocation());
8753837f427SRui Ueyama   cmd->inOverlay = true;
876a582419aSGeorge Rimar   expect("{");
877dbd0ad33SPeter Smith   while (!errorCount() && !consume("}")) {
878dbd0ad33SPeter Smith     uint64_t withFlags = 0;
879dbd0ad33SPeter Smith     uint64_t withoutFlags = 0;
880dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
881dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
8826188fd49SFangrui Song     cmd->commands.push_back(
883dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags));
884dbd0ad33SPeter Smith   }
8853837f427SRui Ueyama   return cmd;
886a582419aSGeorge Rimar }
887a582419aSGeorge Rimar 
8883837f427SRui Ueyama OutputSection *ScriptParser::readOutputSectionDescription(StringRef outSec) {
8893837f427SRui Ueyama   OutputSection *cmd =
8903837f427SRui Ueyama       script->createOutputSection(outSec, getCurrentLocation());
8913271d370SRui Ueyama 
8923837f427SRui Ueyama   size_t symbolsReferenced = script->referencedSymbols.size();
893c4df670dSGeorge Rimar 
8943271d370SRui Ueyama   if (peek() != ":")
8953837f427SRui Ueyama     readSectionAddressType(cmd);
8962ec34544SRui Ueyama   expect(":");
8972ec34544SRui Ueyama 
8983837f427SRui Ueyama   std::string location = getCurrentLocation();
8992ec34544SRui Ueyama   if (consume("AT"))
9003837f427SRui Ueyama     cmd->lmaExpr = readParenExpr();
9012ec34544SRui Ueyama   if (consume("ALIGN"))
9023837f427SRui Ueyama     cmd->alignExpr = checkAlignment(readParenExpr(), location);
9032ec34544SRui Ueyama   if (consume("SUBALIGN"))
9043837f427SRui Ueyama     cmd->subalignExpr = checkAlignment(readParenExpr(), location);
9052ec34544SRui Ueyama 
9062ec34544SRui Ueyama   // Parse constraints.
9072ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
9083837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadOnly;
9092ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
9103837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadWrite;
9112ec34544SRui Ueyama   expect("{");
9122ec34544SRui Ueyama 
913b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
9143837f427SRui Ueyama     StringRef tok = next();
9153837f427SRui Ueyama     if (tok == ";") {
9162ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
9173837f427SRui Ueyama     } else if (SymbolAssignment *assign = readAssignment(tok)) {
9186188fd49SFangrui Song       cmd->commands.push_back(assign);
9193837f427SRui Ueyama     } else if (ByteCommand *data = readByteCommand(tok)) {
9206188fd49SFangrui Song       cmd->commands.push_back(data);
9213837f427SRui Ueyama     } else if (tok == "CONSTRUCTORS") {
9222ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
9232ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
9242ec34544SRui Ueyama       // For ELF, we should ignore.
9253837f427SRui Ueyama     } else if (tok == "FILL") {
9260810f16fSGeorge Rimar       // We handle the FILL command as an alias for =fillexp section attribute,
9270810f16fSGeorge Rimar       // which is different from what GNU linkers do.
9280810f16fSGeorge Rimar       // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
929bb7d2b17SGeorgii Rymar       if (peek() != "(")
930bb7d2b17SGeorgii Rymar         setError("( expected, but got " + peek());
9313837f427SRui Ueyama       cmd->filler = readFill();
9323837f427SRui Ueyama     } else if (tok == "SORT") {
9332ec34544SRui Ueyama       readSort();
9343837f427SRui Ueyama     } else if (tok == "INCLUDE") {
9352e9d40d5SRui Ueyama       readInclude();
9362ec34544SRui Ueyama     } else if (peek() == "(") {
9376188fd49SFangrui Song       cmd->commands.push_back(readInputSectionDescription(tok));
9382ec34544SRui Ueyama     } else {
939f49fe218SGeorge Rimar       // We have a file name and no input sections description. It is not a
940f49fe218SGeorge Rimar       // commonly used syntax, but still acceptable. In that case, all sections
941f49fe218SGeorge Rimar       // from the file will be included.
942dbd0ad33SPeter Smith       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
943dbd0ad33SPeter Smith       // handle this case here as it will already have been matched by the
944dbd0ad33SPeter Smith       // case above.
9453837f427SRui Ueyama       auto *isd = make<InputSectionDescription>(tok);
946c42fe247SThomas Preud'homme       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
9476188fd49SFangrui Song       cmd->commands.push_back(isd);
9482ec34544SRui Ueyama     }
9492ec34544SRui Ueyama   }
9502ec34544SRui Ueyama 
9512ec34544SRui Ueyama   if (consume(">"))
952adcd0268SBenjamin Kramer     cmd->memoryRegionName = std::string(next());
9532ec34544SRui Ueyama 
9545d01a8beSGeorge Rimar   if (consume("AT")) {
9555d01a8beSGeorge Rimar     expect(">");
956adcd0268SBenjamin Kramer     cmd->lmaRegionName = std::string(next());
9575d01a8beSGeorge Rimar   }
9585d01a8beSGeorge Rimar 
9593837f427SRui Ueyama   if (cmd->lmaExpr && !cmd->lmaRegionName.empty())
9605d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
9615d01a8beSGeorge Rimar 
9623837f427SRui Ueyama   cmd->phdrs = readOutputSectionPhdrs();
9632ec34544SRui Ueyama 
9640810f16fSGeorge Rimar   if (peek() == "=" || peek().startswith("=")) {
9653837f427SRui Ueyama     inExpr = true;
9660810f16fSGeorge Rimar     consume("=");
9673837f427SRui Ueyama     cmd->filler = readFill();
9683837f427SRui Ueyama     inExpr = false;
9690810f16fSGeorge Rimar   }
9702ec34544SRui Ueyama 
9712ec34544SRui Ueyama   // Consume optional comma following output section command.
9722ec34544SRui Ueyama   consume(",");
9732ec34544SRui Ueyama 
9743837f427SRui Ueyama   if (script->referencedSymbols.size() > symbolsReferenced)
9753837f427SRui Ueyama     cmd->expressionsUseSymbols = true;
9763837f427SRui Ueyama   return cmd;
9772ec34544SRui Ueyama }
9782ec34544SRui Ueyama 
9790810f16fSGeorge Rimar // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
9802ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
9810810f16fSGeorge Rimar // We do not support using symbols in such expressions.
9822ec34544SRui Ueyama //
9838acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
9848acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
9858acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
986bb7d2b17SGeorgii Rymar // Also, we require that expressions with operators must be wrapped into
987bb7d2b17SGeorgii Rymar // round brackets. We did it to resolve the ambiguity when parsing scripts like:
988bb7d2b17SGeorgii Rymar // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
9890810f16fSGeorge Rimar std::array<uint8_t, 4> ScriptParser::readFill() {
990bb7d2b17SGeorgii Rymar   uint64_t value = readPrimary()().val;
9913837f427SRui Ueyama   if (value > UINT32_MAX)
9920810f16fSGeorge Rimar     setError("filler expression result does not fit 32-bit: 0x" +
9933837f427SRui Ueyama              Twine::utohexstr(value));
994b58079d4SRui Ueyama 
9953837f427SRui Ueyama   std::array<uint8_t, 4> buf;
9963837f427SRui Ueyama   write32be(buf.data(), (uint32_t)value);
9973837f427SRui Ueyama   return buf;
9982ec34544SRui Ueyama }
9992ec34544SRui Ueyama 
10003837f427SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
10012ec34544SRui Ueyama   expect("(");
10023837f427SRui Ueyama   SymbolAssignment *cmd = readSymbolAssignment(next());
10033837f427SRui Ueyama   cmd->provide = provide;
10043837f427SRui Ueyama   cmd->hidden = hidden;
10052ec34544SRui Ueyama   expect(")");
10063837f427SRui Ueyama   return cmd;
10072ec34544SRui Ueyama }
10082ec34544SRui Ueyama 
10093837f427SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
1010d30a78b3SGeorge Rimar   // Assert expression returns Dot, so this is equal to ".=."
10113837f427SRui Ueyama   if (tok == "ASSERT")
1012d30a78b3SGeorge Rimar     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
1013d30a78b3SGeorge Rimar 
10143837f427SRui Ueyama   size_t oldPos = pos;
10153837f427SRui Ueyama   SymbolAssignment *cmd = nullptr;
1016e88b76a9SGeorge Rimar   if (peek() == "=" || peek() == "+=")
10173837f427SRui Ueyama     cmd = readSymbolAssignment(tok);
10183837f427SRui Ueyama   else if (tok == "PROVIDE")
10193837f427SRui Ueyama     cmd = readProvideHidden(true, false);
10203837f427SRui Ueyama   else if (tok == "HIDDEN")
10213837f427SRui Ueyama     cmd = readProvideHidden(false, true);
10223837f427SRui Ueyama   else if (tok == "PROVIDE_HIDDEN")
10233837f427SRui Ueyama     cmd = readProvideHidden(true, true);
1024e88b76a9SGeorge Rimar 
10253837f427SRui Ueyama   if (cmd) {
10263837f427SRui Ueyama     cmd->commandString =
10273837f427SRui Ueyama         tok.str() + " " +
10283837f427SRui Ueyama         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1029e88b76a9SGeorge Rimar     expect(";");
10302ec34544SRui Ueyama   }
10313837f427SRui Ueyama   return cmd;
10322ec34544SRui Ueyama }
10332ec34544SRui Ueyama 
10343837f427SRui Ueyama SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1035e7a7ad13SFangrui Song   name = unquote(name);
10363837f427SRui Ueyama   StringRef op = next();
10373837f427SRui Ueyama   assert(op == "=" || op == "+=");
10383837f427SRui Ueyama   Expr e = readExpr();
10393837f427SRui Ueyama   if (op == "+=") {
10403837f427SRui Ueyama     std::string loc = getCurrentLocation();
10413837f427SRui Ueyama     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
10422ec34544SRui Ueyama   }
10433837f427SRui Ueyama   return make<SymbolAssignment>(name, e, getCurrentLocation());
10442ec34544SRui Ueyama }
10452ec34544SRui Ueyama 
10462ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
10472ec34544SRui Ueyama // script expression.
10482ec34544SRui Ueyama Expr ScriptParser::readExpr() {
10492ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
10502ec34544SRui Ueyama   // they apply different tokenization rules.
10513837f427SRui Ueyama   bool orig = inExpr;
10523837f427SRui Ueyama   inExpr = true;
10533837f427SRui Ueyama   Expr e = readExpr1(readPrimary(), 0);
10543837f427SRui Ueyama   inExpr = orig;
10553837f427SRui Ueyama   return e;
10562ec34544SRui Ueyama }
10572ec34544SRui Ueyama 
10583837f427SRui Ueyama Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
10593837f427SRui Ueyama   if (op == "+")
10603837f427SRui Ueyama     return [=] { return add(l(), r()); };
10613837f427SRui Ueyama   if (op == "-")
10623837f427SRui Ueyama     return [=] { return sub(l(), r()); };
10633837f427SRui Ueyama   if (op == "*")
10643837f427SRui Ueyama     return [=] { return l().getValue() * r().getValue(); };
10653837f427SRui Ueyama   if (op == "/") {
10663837f427SRui Ueyama     std::string loc = getCurrentLocation();
10677b91e213SGeorge Rimar     return [=]() -> uint64_t {
10683837f427SRui Ueyama       if (uint64_t rv = r().getValue())
10693837f427SRui Ueyama         return l().getValue() / rv;
10703837f427SRui Ueyama       error(loc + ": division by zero");
1071067617f9SRui Ueyama       return 0;
10727b91e213SGeorge Rimar     };
10737b91e213SGeorge Rimar   }
10743837f427SRui Ueyama   if (op == "%") {
10753837f427SRui Ueyama     std::string loc = getCurrentLocation();
10767b91e213SGeorge Rimar     return [=]() -> uint64_t {
10773837f427SRui Ueyama       if (uint64_t rv = r().getValue())
10783837f427SRui Ueyama         return l().getValue() % rv;
10793837f427SRui Ueyama       error(loc + ": modulo by zero");
1080067617f9SRui Ueyama       return 0;
10817b91e213SGeorge Rimar     };
10827b91e213SGeorge Rimar   }
10833837f427SRui Ueyama   if (op == "<<")
10843837f427SRui Ueyama     return [=] { return l().getValue() << r().getValue(); };
10853837f427SRui Ueyama   if (op == ">>")
10863837f427SRui Ueyama     return [=] { return l().getValue() >> r().getValue(); };
10873837f427SRui Ueyama   if (op == "<")
10883837f427SRui Ueyama     return [=] { return l().getValue() < r().getValue(); };
10893837f427SRui Ueyama   if (op == ">")
10903837f427SRui Ueyama     return [=] { return l().getValue() > r().getValue(); };
10913837f427SRui Ueyama   if (op == ">=")
10923837f427SRui Ueyama     return [=] { return l().getValue() >= r().getValue(); };
10933837f427SRui Ueyama   if (op == "<=")
10943837f427SRui Ueyama     return [=] { return l().getValue() <= r().getValue(); };
10953837f427SRui Ueyama   if (op == "==")
10963837f427SRui Ueyama     return [=] { return l().getValue() == r().getValue(); };
10973837f427SRui Ueyama   if (op == "!=")
10983837f427SRui Ueyama     return [=] { return l().getValue() != r().getValue(); };
10993837f427SRui Ueyama   if (op == "||")
11003837f427SRui Ueyama     return [=] { return l().getValue() || r().getValue(); };
11013837f427SRui Ueyama   if (op == "&&")
11023837f427SRui Ueyama     return [=] { return l().getValue() && r().getValue(); };
11033837f427SRui Ueyama   if (op == "&")
11043837f427SRui Ueyama     return [=] { return bitAnd(l(), r()); };
11053837f427SRui Ueyama   if (op == "|")
11063837f427SRui Ueyama     return [=] { return bitOr(l(), r()); };
11072ec34544SRui Ueyama   llvm_unreachable("invalid operator");
11082ec34544SRui Ueyama }
11092ec34544SRui Ueyama 
11102ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
11112ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
11123837f427SRui Ueyama Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1113b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
11142ec34544SRui Ueyama     // Read an operator and an expression.
11152ec34544SRui Ueyama     if (consume("?"))
11163837f427SRui Ueyama       return readTernary(lhs);
11173837f427SRui Ueyama     StringRef op1 = peek();
11183837f427SRui Ueyama     if (precedence(op1) < minPrec)
11192ec34544SRui Ueyama       break;
11202ec34544SRui Ueyama     skip();
11213837f427SRui Ueyama     Expr rhs = readPrimary();
11222ec34544SRui Ueyama 
11232ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
11242ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
11252ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
11262ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
11272ec34544SRui Ueyama     while (!atEOF()) {
11283837f427SRui Ueyama       StringRef op2 = peek();
11293837f427SRui Ueyama       if (precedence(op2) <= precedence(op1))
11302ec34544SRui Ueyama         break;
11313837f427SRui Ueyama       rhs = readExpr1(rhs, precedence(op2));
11322ec34544SRui Ueyama     }
11332ec34544SRui Ueyama 
11343837f427SRui Ueyama     lhs = combine(op1, lhs, rhs);
11352ec34544SRui Ueyama   }
11363837f427SRui Ueyama   return lhs;
11372ec34544SRui Ueyama }
11382ec34544SRui Ueyama 
11395fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
11403837f427SRui Ueyama   std::string location = getCurrentLocation();
11415fb17128SGeorge Rimar   return [=]() -> uint64_t {
11423837f427SRui Ueyama     if (target)
11433837f427SRui Ueyama       return config->commonPageSize;
11443837f427SRui Ueyama     error(location + ": unable to calculate page size");
11455fb17128SGeorge Rimar     return 4096; // Return a dummy value.
11465fb17128SGeorge Rimar   };
11475fb17128SGeorge Rimar }
11485fb17128SGeorge Rimar 
11495fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
11503837f427SRui Ueyama   StringRef s = readParenLiteral();
11513837f427SRui Ueyama   if (s == "COMMONPAGESIZE")
11525fb17128SGeorge Rimar     return getPageSize();
11533837f427SRui Ueyama   if (s == "MAXPAGESIZE")
11543837f427SRui Ueyama     return [] { return config->maxPageSize; };
11553837f427SRui Ueyama   setError("unknown constant: " + s);
1156b068b037SGeorge Rimar   return [] { return 0; };
11572ec34544SRui Ueyama }
11582ec34544SRui Ueyama 
11595c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
11605c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
11615c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
11623837f427SRui Ueyama static Optional<uint64_t> parseInt(StringRef tok) {
11632ec34544SRui Ueyama   // Hexadecimal
11643837f427SRui Ueyama   uint64_t val;
11653c6f8ca7SMartin Storsjö   if (tok.startswith_insensitive("0x")) {
11663837f427SRui Ueyama     if (!to_integer(tok.substr(2), val, 16))
11674092016bSRui Ueyama       return None;
11683837f427SRui Ueyama     return val;
11694092016bSRui Ueyama   }
11703c6f8ca7SMartin Storsjö   if (tok.endswith_insensitive("H")) {
11713837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 16))
11724092016bSRui Ueyama       return None;
11733837f427SRui Ueyama     return val;
11744092016bSRui Ueyama   }
11752ec34544SRui Ueyama 
11762ec34544SRui Ueyama   // Decimal
11773c6f8ca7SMartin Storsjö   if (tok.endswith_insensitive("K")) {
11783837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
11795c65088fSRui Ueyama       return None;
11803837f427SRui Ueyama     return val * 1024;
11812ec34544SRui Ueyama   }
11823c6f8ca7SMartin Storsjö   if (tok.endswith_insensitive("M")) {
11833837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
11845c65088fSRui Ueyama       return None;
11853837f427SRui Ueyama     return val * 1024 * 1024;
11865c65088fSRui Ueyama   }
11873837f427SRui Ueyama   if (!to_integer(tok, val, 10))
11885c65088fSRui Ueyama     return None;
11893837f427SRui Ueyama   return val;
11902ec34544SRui Ueyama }
11912ec34544SRui Ueyama 
11923837f427SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
11933837f427SRui Ueyama   int size = StringSwitch<int>(tok)
11942ec34544SRui Ueyama                  .Case("BYTE", 1)
11952ec34544SRui Ueyama                  .Case("SHORT", 2)
11962ec34544SRui Ueyama                  .Case("LONG", 4)
11972ec34544SRui Ueyama                  .Case("QUAD", 8)
11982ec34544SRui Ueyama                  .Default(-1);
11993837f427SRui Ueyama   if (size == -1)
12002ec34544SRui Ueyama     return nullptr;
120184bcabcbSGeorge Rimar 
12023837f427SRui Ueyama   size_t oldPos = pos;
12033837f427SRui Ueyama   Expr e = readParenExpr();
12043837f427SRui Ueyama   std::string commandString =
12053837f427SRui Ueyama       tok.str() + " " +
12063837f427SRui Ueyama       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
12073837f427SRui Ueyama   return make<ByteCommand>(e, size, commandString);
12082ec34544SRui Ueyama }
12092ec34544SRui Ueyama 
1210dbd0ad33SPeter Smith static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1211dbd0ad33SPeter Smith   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1212dbd0ad33SPeter Smith     return asInt;
1213dbd0ad33SPeter Smith #define CASE_ENT(enum) #enum, ELF::enum
1214dbd0ad33SPeter Smith   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1215dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_WRITE))
1216dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ALLOC))
1217dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXECINSTR))
1218dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_MERGE))
1219dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_STRINGS))
1220dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_INFO_LINK))
1221dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_LINK_ORDER))
1222dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1223dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_GROUP))
1224dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_TLS))
1225dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_COMPRESSED))
1226dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXCLUDE))
1227dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ARM_PURECODE))
1228dbd0ad33SPeter Smith       .Default(None);
1229dbd0ad33SPeter Smith #undef CASE_ENT
1230dbd0ad33SPeter Smith }
1231dbd0ad33SPeter Smith 
1232dbd0ad33SPeter Smith // Reads the '(' <flags> ')' list of section flags in
1233dbd0ad33SPeter Smith // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1234dbd0ad33SPeter Smith // following form:
1235dbd0ad33SPeter Smith // <flags> ::= <flag>
1236dbd0ad33SPeter Smith //           | <flags> & flag
1237dbd0ad33SPeter Smith // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1238dbd0ad33SPeter Smith // If the first character of <flag> is a ! then this means without flag,
1239dbd0ad33SPeter Smith // otherwise with flag.
1240dbd0ad33SPeter Smith // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1241dbd0ad33SPeter Smith // without flag SHF_WRITE.
1242dbd0ad33SPeter Smith std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1243dbd0ad33SPeter Smith    uint64_t withFlags = 0;
1244dbd0ad33SPeter Smith    uint64_t withoutFlags = 0;
1245dbd0ad33SPeter Smith    expect("(");
1246dbd0ad33SPeter Smith    while (!errorCount()) {
1247dbd0ad33SPeter Smith     StringRef tok = unquote(next());
1248dbd0ad33SPeter Smith     bool without = tok.consume_front("!");
1249dbd0ad33SPeter Smith     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1250dbd0ad33SPeter Smith       if (without)
1251dbd0ad33SPeter Smith         withoutFlags |= *flag;
1252dbd0ad33SPeter Smith       else
1253dbd0ad33SPeter Smith         withFlags |= *flag;
1254dbd0ad33SPeter Smith     } else {
1255dbd0ad33SPeter Smith       setError("unrecognised flag: " + tok);
1256dbd0ad33SPeter Smith     }
1257dbd0ad33SPeter Smith     if (consume(")"))
1258dbd0ad33SPeter Smith       break;
1259dbd0ad33SPeter Smith     if (!consume("&")) {
1260dbd0ad33SPeter Smith       next();
1261dbd0ad33SPeter Smith       setError("expected & or )");
1262dbd0ad33SPeter Smith     }
1263dbd0ad33SPeter Smith   }
1264dbd0ad33SPeter Smith   return std::make_pair(withFlags, withoutFlags);
1265dbd0ad33SPeter Smith }
1266dbd0ad33SPeter Smith 
12672ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
12682ec34544SRui Ueyama   expect("(");
12693837f427SRui Ueyama   bool orig = inExpr;
12703837f427SRui Ueyama   inExpr = false;
12713837f427SRui Ueyama   StringRef tok = next();
12723837f427SRui Ueyama   inExpr = orig;
12732ec34544SRui Ueyama   expect(")");
12743837f427SRui Ueyama   return tok;
12752ec34544SRui Ueyama }
12762ec34544SRui Ueyama 
12773837f427SRui Ueyama static void checkIfExists(OutputSection *cmd, StringRef location) {
12783837f427SRui Ueyama   if (cmd->location.empty() && script->errorOnMissingSection)
12793837f427SRui Ueyama     error(location + ": undefined section " + cmd->name);
128005c4f67cSRafael Espindola }
128105c4f67cSRafael Espindola 
1282e4f385d8SFangrui Song static bool isValidSymbolName(StringRef s) {
1283e4f385d8SFangrui Song   auto valid = [](char c) {
1284e4f385d8SFangrui Song     return isAlnum(c) || c == '$' || c == '.' || c == '_';
1285e4f385d8SFangrui Song   };
1286e4f385d8SFangrui Song   return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1287e4f385d8SFangrui Song }
1288e4f385d8SFangrui Song 
12892ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
12902ec34544SRui Ueyama   if (peek() == "(")
12912ec34544SRui Ueyama     return readParenExpr();
12922ec34544SRui Ueyama 
12935c65088fSRui Ueyama   if (consume("~")) {
12943837f427SRui Ueyama     Expr e = readPrimary();
12953837f427SRui Ueyama     return [=] { return ~e().getValue(); };
12962ec34544SRui Ueyama   }
12976f1d954eSHafiz Abid Qadeer   if (consume("!")) {
12983837f427SRui Ueyama     Expr e = readPrimary();
12993837f427SRui Ueyama     return [=] { return !e().getValue(); };
13006f1d954eSHafiz Abid Qadeer   }
13015c65088fSRui Ueyama   if (consume("-")) {
13023837f427SRui Ueyama     Expr e = readPrimary();
13033837f427SRui Ueyama     return [=] { return -e().getValue(); };
13042ec34544SRui Ueyama   }
13052ec34544SRui Ueyama 
13063837f427SRui Ueyama   StringRef tok = next();
13073837f427SRui Ueyama   std::string location = getCurrentLocation();
13085c65088fSRui Ueyama 
13092ec34544SRui Ueyama   // Built-in functions are parsed here.
13102ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
13113837f427SRui Ueyama   if (tok == "ABSOLUTE") {
13123837f427SRui Ueyama     Expr inner = readParenExpr();
13132ec34544SRui Ueyama     return [=] {
13143837f427SRui Ueyama       ExprValue i = inner();
13153837f427SRui Ueyama       i.forceAbsolute = true;
13163837f427SRui Ueyama       return i;
13172ec34544SRui Ueyama     };
13182ec34544SRui Ueyama   }
13193837f427SRui Ueyama   if (tok == "ADDR") {
13203837f427SRui Ueyama     StringRef name = readParenLiteral();
13213837f427SRui Ueyama     OutputSection *sec = script->getOrCreateOutputSection(name);
13223837f427SRui Ueyama     sec->usedInExpression = true;
132341c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
13243837f427SRui Ueyama       checkIfExists(sec, location);
13253837f427SRui Ueyama       return {sec, false, 0, location};
132641c7ab4aSGeorge Rimar     };
13272ec34544SRui Ueyama   }
13283837f427SRui Ueyama   if (tok == "ALIGN") {
13292ec34544SRui Ueyama     expect("(");
13303837f427SRui Ueyama     Expr e = readExpr();
1331f22ec9ddSGeorge Rimar     if (consume(")")) {
13323837f427SRui Ueyama       e = checkAlignment(e, location);
13333837f427SRui Ueyama       return [=] { return alignTo(script->getDot(), e().getValue()); };
1334f22ec9ddSGeorge Rimar     }
1335b579c439SRui Ueyama     expect(",");
13363837f427SRui Ueyama     Expr e2 = checkAlignment(readExpr(), location);
13372ec34544SRui Ueyama     expect(")");
13383c6de1a6SPetr Hosek     return [=] {
13393837f427SRui Ueyama       ExprValue v = e();
13403837f427SRui Ueyama       v.alignment = e2().getValue();
13413837f427SRui Ueyama       return v;
13423c6de1a6SPetr Hosek     };
13432ec34544SRui Ueyama   }
13443837f427SRui Ueyama   if (tok == "ALIGNOF") {
13453837f427SRui Ueyama     StringRef name = readParenLiteral();
13463837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
1347617e2f98SRui Ueyama     return [=] {
13483837f427SRui Ueyama       checkIfExists(cmd, location);
13493837f427SRui Ueyama       return cmd->alignment;
1350617e2f98SRui Ueyama     };
13512ec34544SRui Ueyama   }
13523837f427SRui Ueyama   if (tok == "ASSERT")
1353d30a78b3SGeorge Rimar     return readAssert();
13543837f427SRui Ueyama   if (tok == "CONSTANT")
13555fb17128SGeorge Rimar     return readConstant();
13563837f427SRui Ueyama   if (tok == "DATA_SEGMENT_ALIGN") {
13572ec34544SRui Ueyama     expect("(");
13583837f427SRui Ueyama     Expr e = readExpr();
13592ec34544SRui Ueyama     expect(",");
13602ec34544SRui Ueyama     readExpr();
13612ec34544SRui Ueyama     expect(")");
136260833f6eSGeorge Rimar     return [=] {
13633837f427SRui Ueyama       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
136460833f6eSGeorge Rimar     };
13652ec34544SRui Ueyama   }
13663837f427SRui Ueyama   if (tok == "DATA_SEGMENT_END") {
13672ec34544SRui Ueyama     expect("(");
13682ec34544SRui Ueyama     expect(".");
13692ec34544SRui Ueyama     expect(")");
13703837f427SRui Ueyama     return [] { return script->getDot(); };
13712ec34544SRui Ueyama   }
13723837f427SRui Ueyama   if (tok == "DATA_SEGMENT_RELRO_END") {
13732ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
13742ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
13752ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
13762ec34544SRui Ueyama     expect("(");
13772ec34544SRui Ueyama     readExpr();
13782ec34544SRui Ueyama     expect(",");
13792ec34544SRui Ueyama     readExpr();
13802ec34544SRui Ueyama     expect(")");
13813837f427SRui Ueyama     Expr e = getPageSize();
13823837f427SRui Ueyama     return [=] { return alignTo(script->getDot(), e().getValue()); };
13832ec34544SRui Ueyama   }
13843837f427SRui Ueyama   if (tok == "DEFINED") {
1385e7a7ad13SFangrui Song     StringRef name = unquote(readParenLiteral());
13861f166edeSHafiz Abid Qadeer     return [=] {
13871f166edeSHafiz Abid Qadeer       Symbol *b = symtab->find(name);
13881f166edeSHafiz Abid Qadeer       return (b && b->isDefined()) ? 1 : 0;
13891f166edeSHafiz Abid Qadeer     };
13902ec34544SRui Ueyama   }
13913837f427SRui Ueyama   if (tok == "LENGTH") {
13923837f427SRui Ueyama     StringRef name = readParenLiteral();
13933837f427SRui Ueyama     if (script->memoryRegions.count(name) == 0) {
13943837f427SRui Ueyama       setError("memory region not defined: " + name);
1395b068b037SGeorge Rimar       return [] { return 0; };
1396b068b037SGeorge Rimar     }
139792b5b980SFangrui Song     return script->memoryRegions[name]->length;
139891b95b61SRui Ueyama   }
13993837f427SRui Ueyama   if (tok == "LOADADDR") {
14003837f427SRui Ueyama     StringRef name = readParenLiteral();
14013837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
14023837f427SRui Ueyama     cmd->usedInExpression = true;
1403617e2f98SRui Ueyama     return [=] {
14043837f427SRui Ueyama       checkIfExists(cmd, location);
14053837f427SRui Ueyama       return cmd->getLMA();
1406617e2f98SRui Ueyama     };
14072ec34544SRui Ueyama   }
1408fa1145a8SIsaac Richter   if (tok == "LOG2CEIL") {
1409fa1145a8SIsaac Richter     expect("(");
1410fa1145a8SIsaac Richter     Expr a = readExpr();
1411fa1145a8SIsaac Richter     expect(")");
1412fa1145a8SIsaac Richter     return [=] {
1413fa1145a8SIsaac Richter       // LOG2CEIL(0) is defined to be 0.
1414fa1145a8SIsaac Richter       return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1415fa1145a8SIsaac Richter     };
1416fa1145a8SIsaac Richter   }
14173837f427SRui Ueyama   if (tok == "MAX" || tok == "MIN") {
1418fd11560fSGeorge Rimar     expect("(");
14193837f427SRui Ueyama     Expr a = readExpr();
1420fd11560fSGeorge Rimar     expect(",");
14213837f427SRui Ueyama     Expr b = readExpr();
1422fd11560fSGeorge Rimar     expect(")");
14233837f427SRui Ueyama     if (tok == "MIN")
14243837f427SRui Ueyama       return [=] { return std::min(a().getValue(), b().getValue()); };
14253837f427SRui Ueyama     return [=] { return std::max(a().getValue(), b().getValue()); };
1426fd11560fSGeorge Rimar   }
14273837f427SRui Ueyama   if (tok == "ORIGIN") {
14283837f427SRui Ueyama     StringRef name = readParenLiteral();
14293837f427SRui Ueyama     if (script->memoryRegions.count(name) == 0) {
14303837f427SRui Ueyama       setError("memory region not defined: " + name);
1431b068b037SGeorge Rimar       return [] { return 0; };
1432b068b037SGeorge Rimar     }
143392b5b980SFangrui Song     return script->memoryRegions[name]->origin;
143491b95b61SRui Ueyama   }
14353837f427SRui Ueyama   if (tok == "SEGMENT_START") {
14362ec34544SRui Ueyama     expect("(");
14372ec34544SRui Ueyama     skip();
14382ec34544SRui Ueyama     expect(",");
14393837f427SRui Ueyama     Expr e = readExpr();
14402ec34544SRui Ueyama     expect(")");
14413837f427SRui Ueyama     return [=] { return e(); };
14422ec34544SRui Ueyama   }
14433837f427SRui Ueyama   if (tok == "SIZEOF") {
14443837f427SRui Ueyama     StringRef name = readParenLiteral();
14453837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
144605c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
144705c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
144805c4f67cSRafael Espindola     // be empty.
14493837f427SRui Ueyama     return [=] { return cmd->size; };
14502ec34544SRui Ueyama   }
14513837f427SRui Ueyama   if (tok == "SIZEOF_HEADERS")
145207837b8fSFangrui Song     return [=] { return elf::getHeaderSize(); };
14532ec34544SRui Ueyama 
14544eb2eccbSRui Ueyama   // Tok is the dot.
14553837f427SRui Ueyama   if (tok == ".")
14563837f427SRui Ueyama     return [=] { return script->getSymbolValue(tok, location); };
14574eb2eccbSRui Ueyama 
14582ec34544SRui Ueyama   // Tok is a literal number.
14593837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
14603837f427SRui Ueyama     return [=] { return *val; };
14612ec34544SRui Ueyama 
14622ec34544SRui Ueyama   // Tok is a symbol name.
14632bf06d93SFangrui Song   if (tok.startswith("\""))
1464e7a7ad13SFangrui Song     tok = unquote(tok);
14652bf06d93SFangrui Song   else if (!isValidSymbolName(tok))
14663837f427SRui Ueyama     setError("malformed number: " + tok);
14673837f427SRui Ueyama   script->referencedSymbols.push_back(tok);
14683837f427SRui Ueyama   return [=] { return script->getSymbolValue(tok, location); };
14692ec34544SRui Ueyama }
14702ec34544SRui Ueyama 
14713837f427SRui Ueyama Expr ScriptParser::readTernary(Expr cond) {
14723837f427SRui Ueyama   Expr l = readExpr();
14732ec34544SRui Ueyama   expect(":");
14743837f427SRui Ueyama   Expr r = readExpr();
14753837f427SRui Ueyama   return [=] { return cond().getValue() ? l() : r(); };
14762ec34544SRui Ueyama }
14772ec34544SRui Ueyama 
14782ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
14792ec34544SRui Ueyama   expect("(");
14803837f427SRui Ueyama   Expr e = readExpr();
14812ec34544SRui Ueyama   expect(")");
14823837f427SRui Ueyama   return e;
14832ec34544SRui Ueyama }
14842ec34544SRui Ueyama 
1485a1c2ee01SFangrui Song SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {
1486a1c2ee01SFangrui Song   SmallVector<StringRef, 0> phdrs;
1487b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
14883837f427SRui Ueyama     StringRef tok = next();
14893837f427SRui Ueyama     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
14902ec34544SRui Ueyama   }
14913837f427SRui Ueyama   return phdrs;
14922ec34544SRui Ueyama }
14932ec34544SRui Ueyama 
14942ec34544SRui Ueyama // Read a program header type name. The next token must be a
14952ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
14962ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
14973837f427SRui Ueyama   StringRef tok = next();
14983837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
14993837f427SRui Ueyama     return *val;
15002ec34544SRui Ueyama 
15013837f427SRui Ueyama   unsigned ret = StringSwitch<unsigned>(tok)
15022ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
15032ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
15042ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
15052ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
15062ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
15072ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
15082ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
15092ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
15102ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
15112ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
15122ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
15132ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
15142ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
15152ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
15162ec34544SRui Ueyama                      .Default(-1);
15172ec34544SRui Ueyama 
15183837f427SRui Ueyama   if (ret == (unsigned)-1) {
15193837f427SRui Ueyama     setError("invalid program header type: " + tok);
15202ec34544SRui Ueyama     return PT_NULL;
15212ec34544SRui Ueyama   }
15223837f427SRui Ueyama   return ret;
15232ec34544SRui Ueyama }
15242ec34544SRui Ueyama 
15252ec34544SRui Ueyama // Reads an anonymous version declaration.
15262ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
152764038ef8SFangrui Song   SmallVector<SymbolVersion, 0> locals;
152864038ef8SFangrui Song   SmallVector<SymbolVersion, 0> globals;
15293837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
1530e28a70daSFangrui Song   for (const SymbolVersion &pat : locals)
153100809c88SFangrui Song     config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat);
1532e28a70daSFangrui Song   for (const SymbolVersion &pat : globals)
153300809c88SFangrui Song     config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat);
15342ec34544SRui Ueyama 
15352ec34544SRui Ueyama   expect(";");
15362ec34544SRui Ueyama }
15372ec34544SRui Ueyama 
15382ec34544SRui Ueyama // Reads a non-anonymous version definition,
15392ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
15403837f427SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef verStr) {
15412ec34544SRui Ueyama   // Read a symbol list.
154264038ef8SFangrui Song   SmallVector<SymbolVersion, 0> locals;
154364038ef8SFangrui Song   SmallVector<SymbolVersion, 0> globals;
15443837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
15452ec34544SRui Ueyama 
15462ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
15473837f427SRui Ueyama   VersionDefinition ver;
15483837f427SRui Ueyama   ver.name = verStr;
154900809c88SFangrui Song   ver.nonLocalPatterns = std::move(globals);
155000809c88SFangrui Song   ver.localPatterns = std::move(locals);
1551e28a70daSFangrui Song   ver.id = config->versionDefinitions.size();
15523837f427SRui Ueyama   config->versionDefinitions.push_back(ver);
15532ec34544SRui Ueyama 
15542ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
15552ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
15562ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
15572ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
15582ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
15595f380403SFangrui Song   if (next() != ";")
15602ec34544SRui Ueyama     expect(";");
15612ec34544SRui Ueyama }
15622ec34544SRui Ueyama 
156349279ca1SFangrui Song bool elf::hasWildcard(StringRef s) {
15643837f427SRui Ueyama   return s.find_first_of("?*[") != StringRef::npos;
15651e77ad14SRui Ueyama }
15661e77ad14SRui Ueyama 
15672ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
156864038ef8SFangrui Song std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
15692ec34544SRui Ueyama ScriptParser::readSymbols() {
157064038ef8SFangrui Song   SmallVector<SymbolVersion, 0> locals;
157164038ef8SFangrui Song   SmallVector<SymbolVersion, 0> globals;
157264038ef8SFangrui Song   SmallVector<SymbolVersion, 0> *v = &globals;
15732ec34544SRui Ueyama 
1574b8a59c8aSBob Haarman   while (!errorCount()) {
15752ec34544SRui Ueyama     if (consume("}"))
15762ec34544SRui Ueyama       break;
15772ec34544SRui Ueyama     if (consumeLabel("local")) {
15783837f427SRui Ueyama       v = &locals;
15792ec34544SRui Ueyama       continue;
15802ec34544SRui Ueyama     }
15812ec34544SRui Ueyama     if (consumeLabel("global")) {
15823837f427SRui Ueyama       v = &globals;
15832ec34544SRui Ueyama       continue;
15842ec34544SRui Ueyama     }
15852ec34544SRui Ueyama 
15862ec34544SRui Ueyama     if (consume("extern")) {
158764038ef8SFangrui Song       SmallVector<SymbolVersion, 0> ext = readVersionExtern();
15883837f427SRui Ueyama       v->insert(v->end(), ext.begin(), ext.end());
15892ec34544SRui Ueyama     } else {
15903837f427SRui Ueyama       StringRef tok = next();
15913837f427SRui Ueyama       v->push_back({unquote(tok), false, hasWildcard(tok)});
15922ec34544SRui Ueyama     }
15932ec34544SRui Ueyama     expect(";");
15942ec34544SRui Ueyama   }
15953837f427SRui Ueyama   return {locals, globals};
15962ec34544SRui Ueyama }
15972ec34544SRui Ueyama 
15982ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
15992ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
160017324d8bSRui Ueyama //
160117324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
160217324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
160364038ef8SFangrui Song SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {
16043837f427SRui Ueyama   StringRef tok = next();
16053837f427SRui Ueyama   bool isCXX = tok == "\"C++\"";
16063837f427SRui Ueyama   if (!isCXX && tok != "\"C\"")
16072ec34544SRui Ueyama     setError("Unknown language");
16082ec34544SRui Ueyama   expect("{");
16092ec34544SRui Ueyama 
161064038ef8SFangrui Song   SmallVector<SymbolVersion, 0> ret;
1611b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
16123837f427SRui Ueyama     StringRef tok = next();
16133837f427SRui Ueyama     ret.push_back(
16143837f427SRui Ueyama         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
161517324d8bSRui Ueyama     if (consume("}"))
16163837f427SRui Ueyama       return ret;
16172ec34544SRui Ueyama     expect(";");
16182ec34544SRui Ueyama   }
16192ec34544SRui Ueyama 
16202ec34544SRui Ueyama   expect("}");
16213837f427SRui Ueyama   return ret;
16222ec34544SRui Ueyama }
16232ec34544SRui Ueyama 
162492b5b980SFangrui Song Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
16253837f427SRui Ueyama                                         StringRef s3) {
16263837f427SRui Ueyama   if (!consume(s1) && !consume(s2) && !consume(s3)) {
16273837f427SRui Ueyama     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
162892b5b980SFangrui Song     return [] { return 0; };
16292ec34544SRui Ueyama   }
16302ec34544SRui Ueyama   expect("=");
163192b5b980SFangrui Song   return readExpr();
16322ec34544SRui Ueyama }
16332ec34544SRui Ueyama 
16342ec34544SRui Ueyama // Parse the MEMORY command as specified in:
16352ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
16362ec34544SRui Ueyama //
16372ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
16382ec34544SRui Ueyama void ScriptParser::readMemory() {
16392ec34544SRui Ueyama   expect("{");
1640b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
16413837f427SRui Ueyama     StringRef tok = next();
16423837f427SRui Ueyama     if (tok == "INCLUDE") {
16432e9d40d5SRui Ueyama       readInclude();
16442e9d40d5SRui Ueyama       continue;
16452e9d40d5SRui Ueyama     }
16462ec34544SRui Ueyama 
16473837f427SRui Ueyama     uint32_t flags = 0;
16488cdf1c1eSIgor Kudrin     uint32_t invFlags = 0;
16493837f427SRui Ueyama     uint32_t negFlags = 0;
16508cdf1c1eSIgor Kudrin     uint32_t negInvFlags = 0;
16512ec34544SRui Ueyama     if (consume("(")) {
16528cdf1c1eSIgor Kudrin       readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);
16532ec34544SRui Ueyama       expect(")");
16542ec34544SRui Ueyama     }
16552ec34544SRui Ueyama     expect(":");
16562ec34544SRui Ueyama 
165792b5b980SFangrui Song     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
16582ec34544SRui Ueyama     expect(",");
165992b5b980SFangrui Song     Expr length = readMemoryAssignment("LENGTH", "len", "l");
16602ec34544SRui Ueyama 
16615f37541cSGeorge Rimar     // Add the memory region to the region map.
16628cdf1c1eSIgor Kudrin     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags,
16638cdf1c1eSIgor Kudrin                                           negFlags, negInvFlags);
16643837f427SRui Ueyama     if (!script->memoryRegions.insert({tok, mr}).second)
16653837f427SRui Ueyama       setError("region '" + tok + "' already defined");
16662ec34544SRui Ueyama   }
16672ec34544SRui Ueyama }
16682ec34544SRui Ueyama 
16692ec34544SRui Ueyama // This function parses the attributes used to match against section
16702ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
16712ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
16728cdf1c1eSIgor Kudrin void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
16738cdf1c1eSIgor Kudrin                                         uint32_t &negFlags,
16748cdf1c1eSIgor Kudrin                                         uint32_t &negInvFlags) {
16753837f427SRui Ueyama   bool invert = false;
16762ec34544SRui Ueyama 
16773837f427SRui Ueyama   for (char c : next().lower()) {
16788cdf1c1eSIgor Kudrin     if (c == '!') {
16793837f427SRui Ueyama       invert = !invert;
16808cdf1c1eSIgor Kudrin       std::swap(flags, negFlags);
16818cdf1c1eSIgor Kudrin       std::swap(invFlags, negInvFlags);
16828cdf1c1eSIgor Kudrin       continue;
16832ec34544SRui Ueyama     }
16848cdf1c1eSIgor Kudrin     if (c == 'w')
16858cdf1c1eSIgor Kudrin       flags |= SHF_WRITE;
16868cdf1c1eSIgor Kudrin     else if (c == 'x')
16878cdf1c1eSIgor Kudrin       flags |= SHF_EXECINSTR;
16888cdf1c1eSIgor Kudrin     else if (c == 'a')
16898cdf1c1eSIgor Kudrin       flags |= SHF_ALLOC;
16908cdf1c1eSIgor Kudrin     else if (c == 'r')
16918cdf1c1eSIgor Kudrin       invFlags |= SHF_WRITE;
16928cdf1c1eSIgor Kudrin     else
16938cdf1c1eSIgor Kudrin       setError("invalid memory region attribute");
16948cdf1c1eSIgor Kudrin   }
16958cdf1c1eSIgor Kudrin 
16968cdf1c1eSIgor Kudrin   if (invert) {
16978cdf1c1eSIgor Kudrin     std::swap(flags, negFlags);
16988cdf1c1eSIgor Kudrin     std::swap(invFlags, negInvFlags);
16998cdf1c1eSIgor Kudrin   }
17002ec34544SRui Ueyama }
17012ec34544SRui Ueyama 
170207837b8fSFangrui Song void elf::readLinkerScript(MemoryBufferRef mb) {
1703439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read linker script",
1704439341b9SJames Henderson                                  mb.getBufferIdentifier());
17053837f427SRui Ueyama   ScriptParser(mb).readLinkerScript();
17062ec34544SRui Ueyama }
17072ec34544SRui Ueyama 
170807837b8fSFangrui Song void elf::readVersionScript(MemoryBufferRef mb) {
1709439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read version script",
1710439341b9SJames Henderson                                  mb.getBufferIdentifier());
17113837f427SRui Ueyama   ScriptParser(mb).readVersionScript();
17122ec34544SRui Ueyama }
17132ec34544SRui Ueyama 
171407837b8fSFangrui Song void elf::readDynamicList(MemoryBufferRef mb) {
1715439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
171607837b8fSFangrui Song   ScriptParser(mb).readDynamicList();
17178c7e8cceSPetr Hosek }
1718bd8cfe65SFangrui Song 
171907837b8fSFangrui Song void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1720439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read defsym input", name);
172107837b8fSFangrui Song   ScriptParser(mb).readDefsym(name);
172207837b8fSFangrui Song }
1723