12ec34544SRui Ueyama //===- ScriptParser.cpp ---------------------------------------------------===//
22ec34544SRui Ueyama //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
62ec34544SRui Ueyama //
72ec34544SRui Ueyama //===----------------------------------------------------------------------===//
805f6b852SRui Ueyama //
905f6b852SRui Ueyama // This file contains a recursive-descendent parser for linker scripts.
1005f6b852SRui Ueyama // Parsed results are stored to Config and Script global objects.
1105f6b852SRui Ueyama //
1205f6b852SRui Ueyama //===----------------------------------------------------------------------===//
132ec34544SRui Ueyama 
142ec34544SRui Ueyama #include "ScriptParser.h"
152ec34544SRui Ueyama #include "Config.h"
162ec34544SRui Ueyama #include "Driver.h"
172ec34544SRui Ueyama #include "InputSection.h"
182ec34544SRui Ueyama #include "LinkerScript.h"
192ec34544SRui Ueyama #include "OutputSections.h"
202ec34544SRui Ueyama #include "ScriptLexer.h"
212ec34544SRui Ueyama #include "Symbols.h"
222ec34544SRui Ueyama #include "Target.h"
232017d52bSRui Ueyama #include "lld/Common/Memory.h"
242ec34544SRui Ueyama #include "llvm/ADT/SmallString.h"
252ec34544SRui Ueyama #include "llvm/ADT/StringRef.h"
260440be4aSRui Ueyama #include "llvm/ADT/StringSet.h"
272ec34544SRui Ueyama #include "llvm/ADT/StringSwitch.h"
28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
292ec34544SRui Ueyama #include "llvm/Support/Casting.h"
302ec34544SRui Ueyama #include "llvm/Support/ErrorHandling.h"
312ec34544SRui Ueyama #include "llvm/Support/FileSystem.h"
32fa1145a8SIsaac Richter #include "llvm/Support/MathExtras.h"
332ec34544SRui Ueyama #include "llvm/Support/Path.h"
34dbd0ad33SPeter Smith #include "llvm/Support/ScopedPrinter.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();
80*899fdf54SFangrui 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);
96a582419aSGeorge Rimar   std::vector<BaseCommand *> readOverlay();
972ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
98dbd0ad33SPeter Smith   std::pair<uint64_t, uint64_t> readInputSectionFlags();
993837f427SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef tok);
1002ec34544SRui Ueyama   StringMatcher readFilePatterns();
1012ec34544SRui Ueyama   std::vector<SectionPattern> 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);
1162ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1172ec34544SRui Ueyama 
1183837f427SRui Ueyama   Expr combine(StringRef op, Expr l, Expr r);
1192ec34544SRui Ueyama   Expr readExpr();
1203837f427SRui Ueyama   Expr readExpr1(Expr lhs, int minPrec);
1212ec34544SRui Ueyama   StringRef readParenLiteral();
1222ec34544SRui Ueyama   Expr readPrimary();
1233837f427SRui Ueyama   Expr readTernary(Expr cond);
1242ec34544SRui Ueyama   Expr readParenExpr();
1252ec34544SRui Ueyama 
1262ec34544SRui Ueyama   // For parsing version script.
1272ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1282ec34544SRui Ueyama   void readAnonymousDeclaration();
1293837f427SRui Ueyama   void readVersionDeclaration(StringRef verStr);
1302ec34544SRui Ueyama 
1312ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1322ec34544SRui Ueyama   readSymbols();
1332ec34544SRui Ueyama 
134fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1353837f427SRui Ueyama   bool isUnderSysroot = false;
1360440be4aSRui Ueyama 
1370440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1383837f427SRui Ueyama   StringSet<> seen;
1392ec34544SRui Ueyama };
14096b3fe02SRui Ueyama } // namespace
1412ec34544SRui Ueyama 
1423837f427SRui Ueyama static StringRef unquote(StringRef s) {
1433837f427SRui Ueyama   if (s.startswith("\""))
1443837f427SRui Ueyama     return s.substr(1, s.size() - 2);
1453837f427SRui Ueyama   return s;
1461e77ad14SRui Ueyama }
1471e77ad14SRui Ueyama 
1482ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1492ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1503837f427SRui Ueyama static void moveAbsRight(ExprValue &a, ExprValue &b) {
1513837f427SRui Ueyama   if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
1523837f427SRui Ueyama     std::swap(a, b);
1533837f427SRui Ueyama   if (!b.isAbsolute())
1543837f427SRui Ueyama     error(a.loc + ": at least one side of the expression must be absolute");
1552ec34544SRui Ueyama }
1562ec34544SRui Ueyama 
1573837f427SRui Ueyama static ExprValue add(ExprValue a, ExprValue b) {
1583837f427SRui Ueyama   moveAbsRight(a, b);
1593837f427SRui Ueyama   return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
1602ec34544SRui Ueyama }
1612ec34544SRui Ueyama 
1623837f427SRui Ueyama static ExprValue sub(ExprValue a, ExprValue b) {
16363a4a98eSRafael Espindola   // The distance between two symbols in sections is absolute.
1643837f427SRui Ueyama   if (!a.isAbsolute() && !b.isAbsolute())
1653837f427SRui Ueyama     return a.getValue() - b.getValue();
1663837f427SRui Ueyama   return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
1672ec34544SRui Ueyama }
1682ec34544SRui Ueyama 
1693837f427SRui Ueyama static ExprValue bitAnd(ExprValue a, ExprValue b) {
1703837f427SRui Ueyama   moveAbsRight(a, b);
1713837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1723837f427SRui Ueyama           (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
1732ec34544SRui Ueyama }
1742ec34544SRui Ueyama 
1753837f427SRui Ueyama static ExprValue bitOr(ExprValue a, ExprValue b) {
1763837f427SRui Ueyama   moveAbsRight(a, b);
1773837f427SRui Ueyama   return {a.sec, a.forceAbsolute,
1783837f427SRui Ueyama           (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
1792ec34544SRui Ueyama }
1802ec34544SRui Ueyama 
1812ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1822ec34544SRui Ueyama   expect("{");
1833837f427SRui Ueyama   std::vector<SymbolVersion> locals;
1843837f427SRui Ueyama   std::vector<SymbolVersion> globals;
1853837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
186d72d97b3SRafael Espindola   expect(";");
187d72d97b3SRafael Espindola 
188d72d97b3SRafael Espindola   if (!atEOF()) {
1892ec34544SRui Ueyama     setError("EOF expected, but got " + next());
190d72d97b3SRafael Espindola     return;
191d72d97b3SRafael Espindola   }
1923837f427SRui Ueyama   if (!locals.empty()) {
193d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
194d72d97b3SRafael Espindola     return;
195d72d97b3SRafael Espindola   }
196d72d97b3SRafael Espindola 
1973837f427SRui Ueyama   for (SymbolVersion v : globals)
1983837f427SRui Ueyama     config->dynamicList.push_back(v);
1992ec34544SRui Ueyama }
2002ec34544SRui Ueyama 
2012ec34544SRui Ueyama void ScriptParser::readVersionScript() {
2022ec34544SRui Ueyama   readVersionScriptCommand();
2032ec34544SRui Ueyama   if (!atEOF())
2042ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2052ec34544SRui Ueyama }
2062ec34544SRui Ueyama 
2072ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2082ec34544SRui Ueyama   if (consume("{")) {
2092ec34544SRui Ueyama     readAnonymousDeclaration();
2102ec34544SRui Ueyama     return;
2112ec34544SRui Ueyama   }
2122ec34544SRui Ueyama 
213b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2143837f427SRui Ueyama     StringRef verStr = next();
2153837f427SRui Ueyama     if (verStr == "{") {
2162ec34544SRui Ueyama       setError("anonymous version definition is used in "
2172ec34544SRui Ueyama                "combination with other version definitions");
2182ec34544SRui Ueyama       return;
2192ec34544SRui Ueyama     }
2202ec34544SRui Ueyama     expect("{");
2213837f427SRui Ueyama     readVersionDeclaration(verStr);
2222ec34544SRui Ueyama   }
2232ec34544SRui Ueyama }
2242ec34544SRui Ueyama 
2252ec34544SRui Ueyama void ScriptParser::readVersion() {
2262ec34544SRui Ueyama   expect("{");
2272ec34544SRui Ueyama   readVersionScriptCommand();
2282ec34544SRui Ueyama   expect("}");
2292ec34544SRui Ueyama }
2302ec34544SRui Ueyama 
2312ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2322ec34544SRui Ueyama   while (!atEOF()) {
2333837f427SRui Ueyama     StringRef tok = next();
2343837f427SRui Ueyama     if (tok == ";")
2352ec34544SRui Ueyama       continue;
2362ec34544SRui Ueyama 
2373837f427SRui Ueyama     if (tok == "ENTRY") {
2382ec34544SRui Ueyama       readEntry();
2393837f427SRui Ueyama     } else if (tok == "EXTERN") {
2402ec34544SRui Ueyama       readExtern();
2413837f427SRui Ueyama     } else if (tok == "GROUP") {
2422ec34544SRui Ueyama       readGroup();
2433837f427SRui Ueyama     } else if (tok == "INCLUDE") {
2442ec34544SRui Ueyama       readInclude();
2453837f427SRui Ueyama     } else if (tok == "INPUT") {
2461d92aa73SRui Ueyama       readInput();
2473837f427SRui Ueyama     } else if (tok == "MEMORY") {
2482ec34544SRui Ueyama       readMemory();
2493837f427SRui Ueyama     } else if (tok == "OUTPUT") {
2502ec34544SRui Ueyama       readOutput();
2513837f427SRui Ueyama     } else if (tok == "OUTPUT_ARCH") {
2522ec34544SRui Ueyama       readOutputArch();
2533837f427SRui Ueyama     } else if (tok == "OUTPUT_FORMAT") {
2542ec34544SRui Ueyama       readOutputFormat();
255*899fdf54SFangrui Song     } else if (tok == "OVERWRITE_SECTIONS") {
256*899fdf54SFangrui Song       readOverwriteSections();
2573837f427SRui Ueyama     } else if (tok == "PHDRS") {
2582ec34544SRui Ueyama       readPhdrs();
2593837f427SRui Ueyama     } else if (tok == "REGION_ALIAS") {
2605f37541cSGeorge Rimar       readRegionAlias();
2613837f427SRui Ueyama     } else if (tok == "SEARCH_DIR") {
2622ec34544SRui Ueyama       readSearchDir();
2633837f427SRui Ueyama     } else if (tok == "SECTIONS") {
2642ec34544SRui Ueyama       readSections();
2653837f427SRui Ueyama     } else if (tok == "TARGET") {
266e262bb1aSRui Ueyama       readTarget();
2673837f427SRui Ueyama     } else if (tok == "VERSION") {
2682ec34544SRui Ueyama       readVersion();
2693837f427SRui Ueyama     } else if (SymbolAssignment *cmd = readAssignment(tok)) {
2703837f427SRui Ueyama       script->sectionCommands.push_back(cmd);
2712ec34544SRui Ueyama     } else {
2723837f427SRui Ueyama       setError("unknown directive: " + tok);
2732ec34544SRui Ueyama     }
2742ec34544SRui Ueyama   }
2752ec34544SRui Ueyama }
2762ec34544SRui Ueyama 
2773837f427SRui Ueyama void ScriptParser::readDefsym(StringRef name) {
278c1522816SGeorge Rimar   if (errorCount())
279c1522816SGeorge Rimar     return;
2803837f427SRui Ueyama   Expr e = readExpr();
2818c7e8cceSPetr Hosek   if (!atEOF())
2828c7e8cceSPetr Hosek     setError("EOF expected, but got " + next());
2833837f427SRui Ueyama   SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation());
2843837f427SRui Ueyama   script->sectionCommands.push_back(cmd);
2858c7e8cceSPetr Hosek }
2868c7e8cceSPetr Hosek 
2873837f427SRui Ueyama void ScriptParser::addFile(StringRef s) {
2883837f427SRui Ueyama   if (isUnderSysroot && s.startswith("/")) {
2893837f427SRui Ueyama     SmallString<128> pathData;
2903837f427SRui Ueyama     StringRef path = (config->sysroot + s).toStringRef(pathData);
2913837f427SRui Ueyama     if (sys::fs::exists(path)) {
29249a3ad21SRui Ueyama       driver->addFile(saver.save(path), /*withLOption=*/false);
2932ec34544SRui Ueyama       return;
2942ec34544SRui Ueyama     }
2952ec34544SRui Ueyama   }
2962ec34544SRui Ueyama 
2973837f427SRui Ueyama   if (s.startswith("/")) {
298c384ca3cSFangrui Song     // Case 1: s is an absolute path. Just open it.
29949a3ad21SRui Ueyama     driver->addFile(s, /*withLOption=*/false);
3003837f427SRui Ueyama   } else if (s.startswith("=")) {
301c384ca3cSFangrui Song     // Case 2: relative to the sysroot.
3023837f427SRui Ueyama     if (config->sysroot.empty())
30349a3ad21SRui Ueyama       driver->addFile(s.substr(1), /*withLOption=*/false);
3042ec34544SRui Ueyama     else
305136d27abSRui Ueyama       driver->addFile(saver.save(config->sysroot + "/" + s.substr(1)),
30649a3ad21SRui Ueyama                       /*withLOption=*/false);
3073837f427SRui Ueyama   } else if (s.startswith("-l")) {
308c384ca3cSFangrui Song     // Case 3: search in the list of library paths.
3093837f427SRui Ueyama     driver->addLibrary(s.substr(2));
310c384ca3cSFangrui Song   } else {
311c384ca3cSFangrui Song     // Case 4: s is a relative path. Search in the directory of the script file.
312c384ca3cSFangrui Song     std::string filename = std::string(getCurrentMB().getBufferIdentifier());
313c384ca3cSFangrui Song     StringRef directory = sys::path::parent_path(filename);
314c384ca3cSFangrui Song     if (!directory.empty()) {
315c384ca3cSFangrui Song       SmallString<0> path(directory);
316c384ca3cSFangrui Song       sys::path::append(path, s);
317c384ca3cSFangrui Song       if (sys::fs::exists(path)) {
318c384ca3cSFangrui Song         driver->addFile(path, /*withLOption=*/false);
319c384ca3cSFangrui Song         return;
320c384ca3cSFangrui Song       }
321c384ca3cSFangrui Song     }
322c384ca3cSFangrui Song     // Then search in the current working directory.
323c384ca3cSFangrui Song     if (sys::fs::exists(s)) {
32449a3ad21SRui Ueyama       driver->addFile(s, /*withLOption=*/false);
3252ec34544SRui Ueyama     } else {
326c384ca3cSFangrui Song       // Finally, search in the list of library paths.
3273837f427SRui Ueyama       if (Optional<std::string> path = findFromSearchPaths(s))
32849a3ad21SRui Ueyama         driver->addFile(saver.save(*path), /*withLOption=*/true);
3292ec34544SRui Ueyama       else
3303837f427SRui Ueyama         setError("unable to find " + s);
3312ec34544SRui Ueyama     }
3322ec34544SRui Ueyama   }
333c384ca3cSFangrui Song }
3342ec34544SRui Ueyama 
3352ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3362ec34544SRui Ueyama   expect("(");
3373837f427SRui Ueyama   bool orig = config->asNeeded;
3383837f427SRui Ueyama   config->asNeeded = true;
339b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3402ec34544SRui Ueyama     addFile(unquote(next()));
3413837f427SRui Ueyama   config->asNeeded = orig;
3422ec34544SRui Ueyama }
3432ec34544SRui Ueyama 
3442ec34544SRui Ueyama void ScriptParser::readEntry() {
3452ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3462ec34544SRui Ueyama   expect("(");
3473837f427SRui Ueyama   StringRef tok = next();
3483837f427SRui Ueyama   if (config->entry.empty())
3493837f427SRui Ueyama     config->entry = tok;
3502ec34544SRui Ueyama   expect(")");
3512ec34544SRui Ueyama }
3522ec34544SRui Ueyama 
3532ec34544SRui Ueyama void ScriptParser::readExtern() {
3542ec34544SRui Ueyama   expect("(");
355b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3563837f427SRui Ueyama     config->undefined.push_back(unquote(next()));
3572ec34544SRui Ueyama }
3582ec34544SRui Ueyama 
3592ec34544SRui Ueyama void ScriptParser::readGroup() {
3603837f427SRui Ueyama   bool orig = InputFile::isInGroup;
3613837f427SRui Ueyama   InputFile::isInGroup = true;
3621d92aa73SRui Ueyama   readInput();
3633837f427SRui Ueyama   InputFile::isInGroup = orig;
3643837f427SRui Ueyama   if (!orig)
3653837f427SRui Ueyama     ++InputFile::nextGroupId;
3662ec34544SRui Ueyama }
3672ec34544SRui Ueyama 
3682ec34544SRui Ueyama void ScriptParser::readInclude() {
3693837f427SRui Ueyama   StringRef tok = unquote(next());
3702ec34544SRui Ueyama 
3713837f427SRui Ueyama   if (!seen.insert(tok).second) {
3720440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3730440be4aSRui Ueyama     return;
3740440be4aSRui Ueyama   }
3750440be4aSRui Ueyama 
3763837f427SRui Ueyama   if (Optional<std::string> path = searchScript(tok)) {
3773837f427SRui Ueyama     if (Optional<MemoryBufferRef> mb = readFile(*path))
3783837f427SRui Ueyama       tokenize(*mb);
3792ec34544SRui Ueyama     return;
3802ec34544SRui Ueyama   }
3813837f427SRui Ueyama   setError("cannot find linker script " + tok);
3822ec34544SRui Ueyama }
3832ec34544SRui Ueyama 
3841d92aa73SRui Ueyama void ScriptParser::readInput() {
3851d92aa73SRui Ueyama   expect("(");
3861d92aa73SRui Ueyama   while (!errorCount() && !consume(")")) {
3871d92aa73SRui Ueyama     if (consume("AS_NEEDED"))
3881d92aa73SRui Ueyama       readAsNeeded();
3891d92aa73SRui Ueyama     else
3901d92aa73SRui Ueyama       addFile(unquote(next()));
3911d92aa73SRui Ueyama   }
3921d92aa73SRui Ueyama }
3931d92aa73SRui Ueyama 
3942ec34544SRui Ueyama void ScriptParser::readOutput() {
3952ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3962ec34544SRui Ueyama   expect("(");
3973837f427SRui Ueyama   StringRef tok = next();
3983837f427SRui Ueyama   if (config->outputFile.empty())
3993837f427SRui Ueyama     config->outputFile = unquote(tok);
4002ec34544SRui Ueyama   expect(")");
4012ec34544SRui Ueyama }
4022ec34544SRui Ueyama 
4032ec34544SRui Ueyama void ScriptParser::readOutputArch() {
4042ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
4052ec34544SRui Ueyama   expect("(");
406b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4072ec34544SRui Ueyama     skip();
4082ec34544SRui Ueyama }
4092ec34544SRui Ueyama 
4103837f427SRui Ueyama static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
4113837f427SRui Ueyama   return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
4124f8c8228SRui Ueyama       .Case("elf32-i386", {ELF32LEKind, EM_386})
4134f8c8228SRui Ueyama       .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
4144f8c8228SRui Ueyama       .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
4154f8c8228SRui Ueyama       .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
41619b134ccSDimitry Andric       .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
4174f8c8228SRui Ueyama       .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
4187605a9a0SFangrui Song       .Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64})
4194134143cSRui Ueyama       .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
420275eb828SBrandon Bergren       .Case("elf32-powerpcle", {ELF32LEKind, EM_PPC})
4214f8c8228SRui Ueyama       .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
4224f8c8228SRui Ueyama       .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
4234f8c8228SRui Ueyama       .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
4244134143cSRui Ueyama       .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
4254f8c8228SRui Ueyama       .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
4264f8c8228SRui Ueyama       .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
4274f8c8228SRui Ueyama       .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
4284f8c8228SRui Ueyama       .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
4294f8c8228SRui Ueyama       .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
43044d908d7SFangrui Song       .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})
43144d908d7SFangrui Song       .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})
432aff950e9SLemonBoy       .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9})
43392c6141cSLemonBoy       .Case("elf32-msp430", {ELF32LEKind, EM_MSP430})
4344f8c8228SRui Ueyama       .Default({ELFNoneKind, EM_NONE});
435ea8cd00aSRui Ueyama }
436ea8cd00aSRui Ueyama 
437eea34aaeSFangrui Song // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
438eea34aaeSFangrui Song // big if -EB is specified, little if -EL is specified, or default if neither is
439eea34aaeSFangrui Song // specified.
4402ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
4412ec34544SRui Ueyama   expect("(");
442ea8cd00aSRui Ueyama 
443eea34aaeSFangrui Song   StringRef s;
4442822852fSShoaib Meenai   config->bfdname = unquote(next());
445eea34aaeSFangrui Song   if (!consume(")")) {
446eea34aaeSFangrui Song     expect(",");
447eea34aaeSFangrui Song     s = unquote(next());
448eea34aaeSFangrui Song     if (config->optEB)
449eea34aaeSFangrui Song       config->bfdname = s;
450eea34aaeSFangrui Song     expect(",");
451eea34aaeSFangrui Song     s = unquote(next());
452eea34aaeSFangrui Song     if (config->optEL)
453eea34aaeSFangrui Song       config->bfdname = s;
454eea34aaeSFangrui Song     consume(")");
455eea34aaeSFangrui Song   }
456eea34aaeSFangrui Song   s = config->bfdname;
4573837f427SRui Ueyama   if (s.consume_back("-freebsd"))
4583837f427SRui Ueyama     config->osabi = ELFOSABI_FREEBSD;
4594f8c8228SRui Ueyama 
4603837f427SRui Ueyama   std::tie(config->ekind, config->emachine) = parseBfdName(s);
4613837f427SRui Ueyama   if (config->emachine == EM_NONE)
4622822852fSShoaib Meenai     setError("unknown output format name: " + config->bfdname);
4633837f427SRui Ueyama   if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
4643837f427SRui Ueyama     config->mipsN32Abi = true;
46592c6141cSLemonBoy   if (config->emachine == EM_MSP430)
46692c6141cSLemonBoy     config->osabi = ELFOSABI_STANDALONE;
4672ec34544SRui Ueyama }
4682ec34544SRui Ueyama 
4692ec34544SRui Ueyama void ScriptParser::readPhdrs() {
4702ec34544SRui Ueyama   expect("{");
4712ec34544SRui Ueyama 
472b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4733837f427SRui Ueyama     PhdrsCommand cmd;
4743837f427SRui Ueyama     cmd.name = next();
4753837f427SRui Ueyama     cmd.type = readPhdrType();
476b579c439SRui Ueyama 
477b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
478b579c439SRui Ueyama       if (consume("FILEHDR"))
4793837f427SRui Ueyama         cmd.hasFilehdr = true;
480b579c439SRui Ueyama       else if (consume("PHDRS"))
4813837f427SRui Ueyama         cmd.hasPhdrs = true;
482b579c439SRui Ueyama       else if (consume("AT"))
4833837f427SRui Ueyama         cmd.lmaExpr = readParenExpr();
484b579c439SRui Ueyama       else if (consume("FLAGS"))
4853837f427SRui Ueyama         cmd.flags = readParenExpr()().getValue();
486b579c439SRui Ueyama       else
487b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
488b579c439SRui Ueyama     }
4890ae2c24cSRui Ueyama 
4903837f427SRui Ueyama     script->phdrsCommands.push_back(cmd);
4912ec34544SRui Ueyama   }
4922ec34544SRui Ueyama }
4932ec34544SRui Ueyama 
4945f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4955f37541cSGeorge Rimar   expect("(");
4963837f427SRui Ueyama   StringRef alias = unquote(next());
4975f37541cSGeorge Rimar   expect(",");
4983837f427SRui Ueyama   StringRef name = next();
4995f37541cSGeorge Rimar   expect(")");
5005f37541cSGeorge Rimar 
5013837f427SRui Ueyama   if (script->memoryRegions.count(alias))
5023837f427SRui Ueyama     setError("redefinition of memory region '" + alias + "'");
5033837f427SRui Ueyama   if (!script->memoryRegions.count(name))
5043837f427SRui Ueyama     setError("memory region '" + name + "' is not defined");
5053837f427SRui Ueyama   script->memoryRegions.insert({alias, script->memoryRegions[name]});
5065f37541cSGeorge Rimar }
5075f37541cSGeorge Rimar 
5082ec34544SRui Ueyama void ScriptParser::readSearchDir() {
5092ec34544SRui Ueyama   expect("(");
5103837f427SRui Ueyama   StringRef tok = next();
5113837f427SRui Ueyama   if (!config->nostdlib)
5123837f427SRui Ueyama     config->searchPaths.push_back(unquote(tok));
5132ec34544SRui Ueyama   expect(")");
5142ec34544SRui Ueyama }
5152ec34544SRui Ueyama 
516a582419aSGeorge Rimar // This reads an overlay description. Overlays are used to describe output
517a582419aSGeorge Rimar // sections that use the same virtual memory range and normally would trigger
518a582419aSGeorge Rimar // linker's sections sanity check failures.
519a582419aSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
520a582419aSGeorge Rimar std::vector<BaseCommand *> ScriptParser::readOverlay() {
521a582419aSGeorge Rimar   // VA and LMA expressions are optional, though for simplicity of
522a582419aSGeorge Rimar   // implementation we assume they are not. That is what OVERLAY was designed
523a582419aSGeorge Rimar   // for first of all: to allow sections with overlapping VAs at different LMAs.
5243837f427SRui Ueyama   Expr addrExpr = readExpr();
525a582419aSGeorge Rimar   expect(":");
526a582419aSGeorge Rimar   expect("AT");
5273837f427SRui Ueyama   Expr lmaExpr = readParenExpr();
528a582419aSGeorge Rimar   expect("{");
529a582419aSGeorge Rimar 
5303837f427SRui Ueyama   std::vector<BaseCommand *> v;
5313837f427SRui Ueyama   OutputSection *prev = nullptr;
532a582419aSGeorge Rimar   while (!errorCount() && !consume("}")) {
533a582419aSGeorge Rimar     // VA is the same for all sections. The LMAs are consecutive in memory
534a582419aSGeorge Rimar     // starting from the base load address specified.
5353837f427SRui Ueyama     OutputSection *os = readOverlaySectionDescription();
5363837f427SRui Ueyama     os->addrExpr = addrExpr;
5373837f427SRui Ueyama     if (prev)
5383837f427SRui Ueyama       os->lmaExpr = [=] { return prev->getLMA() + prev->size; };
539a582419aSGeorge Rimar     else
5403837f427SRui Ueyama       os->lmaExpr = lmaExpr;
5413837f427SRui Ueyama     v.push_back(os);
5423837f427SRui Ueyama     prev = os;
543a582419aSGeorge Rimar   }
544a582419aSGeorge Rimar 
545a582419aSGeorge Rimar   // According to the specification, at the end of the overlay, the location
546a582419aSGeorge Rimar   // counter should be equal to the overlay base address plus size of the
547a582419aSGeorge Rimar   // largest section seen in the overlay.
548a582419aSGeorge Rimar   // Here we want to create the Dot assignment command to achieve that.
5493837f427SRui Ueyama   Expr moveDot = [=] {
5503837f427SRui Ueyama     uint64_t max = 0;
5513837f427SRui Ueyama     for (BaseCommand *cmd : v)
5523837f427SRui Ueyama       max = std::max(max, cast<OutputSection>(cmd)->size);
5533837f427SRui Ueyama     return addrExpr().getValue() + max;
554a582419aSGeorge Rimar   };
5553837f427SRui Ueyama   v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation()));
5563837f427SRui Ueyama   return v;
557a582419aSGeorge Rimar }
558a582419aSGeorge Rimar 
559*899fdf54SFangrui Song void ScriptParser::readOverwriteSections() {
560*899fdf54SFangrui Song   expect("{");
561*899fdf54SFangrui Song   while (!errorCount() && !consume("}"))
562*899fdf54SFangrui Song     script->overwriteSections.push_back(readOutputSectionDescription(next()));
563*899fdf54SFangrui Song }
564*899fdf54SFangrui Song 
5652ec34544SRui Ueyama void ScriptParser::readSections() {
5662ec34544SRui Ueyama   expect("{");
5673837f427SRui Ueyama   std::vector<BaseCommand *> v;
568b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
5693837f427SRui Ueyama     StringRef tok = next();
5703837f427SRui Ueyama     if (tok == "OVERLAY") {
5713837f427SRui Ueyama       for (BaseCommand *cmd : readOverlay())
5723837f427SRui Ueyama         v.push_back(cmd);
573a582419aSGeorge Rimar       continue;
5743837f427SRui Ueyama     } else if (tok == "INCLUDE") {
5752e9d40d5SRui Ueyama       readInclude();
5762e9d40d5SRui Ueyama       continue;
577a582419aSGeorge Rimar     }
578a582419aSGeorge Rimar 
5793837f427SRui Ueyama     if (BaseCommand *cmd = readAssignment(tok))
5803837f427SRui Ueyama       v.push_back(cmd);
581d30a78b3SGeorge Rimar     else
5823837f427SRui Ueyama       v.push_back(readOutputSectionDescription(tok));
5832ec34544SRui Ueyama   }
5847c426fb1SFangrui Song   script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),
5857c426fb1SFangrui Song                                  v.end());
5869e2c8a9dSGeorge Rimar 
5877c426fb1SFangrui Song   if (atEOF() || !consume("INSERT")) {
5887c426fb1SFangrui Song     script->hasSectionsCommand = true;
5899e2c8a9dSGeorge Rimar     return;
5909e2c8a9dSGeorge Rimar   }
5919e2c8a9dSGeorge Rimar 
5927c426fb1SFangrui Song   bool isAfter = false;
5937c426fb1SFangrui Song   if (consume("AFTER"))
5947c426fb1SFangrui Song     isAfter = true;
5957c426fb1SFangrui Song   else if (!consume("BEFORE"))
5967c426fb1SFangrui Song     setError("expected AFTER/BEFORE, but got '" + next() + "'");
5977c426fb1SFangrui Song   StringRef where = next();
5987c426fb1SFangrui Song   for (BaseCommand *cmd : v)
5997c426fb1SFangrui Song     if (auto *os = dyn_cast<OutputSection>(cmd))
600*899fdf54SFangrui Song       script->insertCommands.push_back({os->name, isAfter, where});
6012ec34544SRui Ueyama }
6022ec34544SRui Ueyama 
603e262bb1aSRui Ueyama void ScriptParser::readTarget() {
604e262bb1aSRui Ueyama   // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
605e262bb1aSRui Ueyama   // we accept only a limited set of BFD names (i.e. "elf" or "binary")
606e262bb1aSRui Ueyama   // for --format. We recognize only /^elf/ and "binary" in the linker
607e262bb1aSRui Ueyama   // script as well.
608e262bb1aSRui Ueyama   expect("(");
6093837f427SRui Ueyama   StringRef tok = next();
610e262bb1aSRui Ueyama   expect(")");
611e262bb1aSRui Ueyama 
6123837f427SRui Ueyama   if (tok.startswith("elf"))
6133837f427SRui Ueyama     config->formatBinary = false;
6143837f427SRui Ueyama   else if (tok == "binary")
6153837f427SRui Ueyama     config->formatBinary = true;
616e262bb1aSRui Ueyama   else
6173837f427SRui Ueyama     setError("unknown target: " + tok);
618e262bb1aSRui Ueyama }
619e262bb1aSRui Ueyama 
6203837f427SRui Ueyama static int precedence(StringRef op) {
6213837f427SRui Ueyama   return StringSwitch<int>(op)
622a5005482SGeorge Rimar       .Cases("*", "/", "%", 8)
623a5005482SGeorge Rimar       .Cases("+", "-", 7)
624a5005482SGeorge Rimar       .Cases("<<", ">>", 6)
625a5005482SGeorge Rimar       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
626a5005482SGeorge Rimar       .Case("&", 4)
627a5005482SGeorge Rimar       .Case("|", 3)
628a5005482SGeorge Rimar       .Case("&&", 2)
629a5005482SGeorge Rimar       .Case("||", 1)
6302ec34544SRui Ueyama       .Default(-1);
6312ec34544SRui Ueyama }
6322ec34544SRui Ueyama 
6332ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
634c42fe247SThomas Preud'homme   StringMatcher Matcher;
635c42fe247SThomas Preud'homme 
636b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
637c42fe247SThomas Preud'homme     Matcher.addPattern(SingleStringMatcher(next()));
638c42fe247SThomas Preud'homme   return Matcher;
6392ec34544SRui Ueyama }
6402ec34544SRui Ueyama 
6412a9aed0eSFangrui Song SortSectionPolicy ScriptParser::peekSortKind() {
6422a9aed0eSFangrui Song   return StringSwitch<SortSectionPolicy>(peek())
6432a9aed0eSFangrui Song       .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)
6442a9aed0eSFangrui Song       .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)
6452a9aed0eSFangrui Song       .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)
6462a9aed0eSFangrui Song       .Case("SORT_NONE", SortSectionPolicy::None)
6472a9aed0eSFangrui Song       .Default(SortSectionPolicy::Default);
6482a9aed0eSFangrui Song }
6492a9aed0eSFangrui Song 
6502ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
6512a9aed0eSFangrui Song   SortSectionPolicy ret = peekSortKind();
6522a9aed0eSFangrui Song   if (ret != SortSectionPolicy::Default)
6532a9aed0eSFangrui Song     skip();
6542a9aed0eSFangrui Song   return ret;
6552ec34544SRui Ueyama }
6562ec34544SRui Ueyama 
65703fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
65803fc8d1eSRui Ueyama //
65903fc8d1eSRui Ueyama // <contents> ::= <elem>*
66003fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
66103fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
66203fc8d1eSRui Ueyama //
66303fc8d1eSRui Ueyama // For example,
66403fc8d1eSRui Ueyama //
66503fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
66603fc8d1eSRui Ueyama //
66703fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
66803fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
66903fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
6702ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
6713837f427SRui Ueyama   std::vector<SectionPattern> ret;
672b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
6733837f427SRui Ueyama     StringMatcher excludeFilePat;
6742ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
6752ec34544SRui Ueyama       expect("(");
6763837f427SRui Ueyama       excludeFilePat = readFilePatterns();
6772ec34544SRui Ueyama     }
6782ec34544SRui Ueyama 
679c42fe247SThomas Preud'homme     StringMatcher SectionMatcher;
6802a9aed0eSFangrui Song     // Break if the next token is ), EXCLUDE_FILE, or SORT*.
6812a9aed0eSFangrui Song     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" &&
6822a9aed0eSFangrui Song            peekSortKind() == SortSectionPolicy::Default)
683c42fe247SThomas Preud'homme       SectionMatcher.addPattern(unquote(next()));
6842ec34544SRui Ueyama 
685c42fe247SThomas Preud'homme     if (!SectionMatcher.empty())
686c42fe247SThomas Preud'homme       ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
6872a9aed0eSFangrui Song     else if (excludeFilePat.empty())
6882a9aed0eSFangrui Song       break;
6892ec34544SRui Ueyama     else
6902ec34544SRui Ueyama       setError("section pattern is expected");
6912ec34544SRui Ueyama   }
6923837f427SRui Ueyama   return ret;
6932ec34544SRui Ueyama }
6942ec34544SRui Ueyama 
6952ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
6962ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
6972ec34544SRui Ueyama //
6982ec34544SRui Ueyama // <patterns> ::= <section-list>
6992ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
7002ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
7012ec34544SRui Ueyama //
7022ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
7032ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
7042ec34544SRui Ueyama //
7052ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
7062ec34544SRui Ueyama InputSectionDescription *
707dbd0ad33SPeter Smith ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
708dbd0ad33SPeter Smith                                     uint64_t withoutFlags) {
709dbd0ad33SPeter Smith   auto *cmd =
710dbd0ad33SPeter Smith       make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
7112ec34544SRui Ueyama   expect("(");
7122ec34544SRui Ueyama 
713b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
7143837f427SRui Ueyama     SortSectionPolicy outer = readSortKind();
7153837f427SRui Ueyama     SortSectionPolicy inner = SortSectionPolicy::Default;
7163837f427SRui Ueyama     std::vector<SectionPattern> v;
7173837f427SRui Ueyama     if (outer != SortSectionPolicy::Default) {
7182ec34544SRui Ueyama       expect("(");
7193837f427SRui Ueyama       inner = readSortKind();
7203837f427SRui Ueyama       if (inner != SortSectionPolicy::Default) {
7212ec34544SRui Ueyama         expect("(");
7223837f427SRui Ueyama         v = readInputSectionsList();
7232ec34544SRui Ueyama         expect(")");
7242ec34544SRui Ueyama       } else {
7253837f427SRui Ueyama         v = readInputSectionsList();
7262ec34544SRui Ueyama       }
7272ec34544SRui Ueyama       expect(")");
7282ec34544SRui Ueyama     } else {
7293837f427SRui Ueyama       v = readInputSectionsList();
7302ec34544SRui Ueyama     }
7312ec34544SRui Ueyama 
7323837f427SRui Ueyama     for (SectionPattern &pat : v) {
7333837f427SRui Ueyama       pat.sortInner = inner;
7343837f427SRui Ueyama       pat.sortOuter = outer;
7352ec34544SRui Ueyama     }
7362ec34544SRui Ueyama 
7373837f427SRui Ueyama     std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
7382ec34544SRui Ueyama   }
7393837f427SRui Ueyama   return cmd;
7402ec34544SRui Ueyama }
7412ec34544SRui Ueyama 
7422ec34544SRui Ueyama InputSectionDescription *
7433837f427SRui Ueyama ScriptParser::readInputSectionDescription(StringRef tok) {
7442ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
7452ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
746dbd0ad33SPeter Smith   uint64_t withFlags = 0;
747dbd0ad33SPeter Smith   uint64_t withoutFlags = 0;
7483837f427SRui Ueyama   if (tok == "KEEP") {
7492ec34544SRui Ueyama     expect("(");
750dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
751dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
752dbd0ad33SPeter Smith     InputSectionDescription *cmd =
753dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags);
7542ec34544SRui Ueyama     expect(")");
7553837f427SRui Ueyama     script->keptSections.push_back(cmd);
7563837f427SRui Ueyama     return cmd;
7572ec34544SRui Ueyama   }
758dbd0ad33SPeter Smith   if (tok == "INPUT_SECTION_FLAGS") {
759dbd0ad33SPeter Smith     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
760dbd0ad33SPeter Smith     tok = next();
761dbd0ad33SPeter Smith   }
762dbd0ad33SPeter Smith   return readInputSectionRules(tok, withFlags, withoutFlags);
7632ec34544SRui Ueyama }
7642ec34544SRui Ueyama 
7652ec34544SRui Ueyama void ScriptParser::readSort() {
7662ec34544SRui Ueyama   expect("(");
7672ec34544SRui Ueyama   expect("CONSTRUCTORS");
7682ec34544SRui Ueyama   expect(")");
7692ec34544SRui Ueyama }
7702ec34544SRui Ueyama 
771d30a78b3SGeorge Rimar Expr ScriptParser::readAssert() {
7722ec34544SRui Ueyama   expect("(");
7733837f427SRui Ueyama   Expr e = readExpr();
7742ec34544SRui Ueyama   expect(",");
7753837f427SRui Ueyama   StringRef msg = unquote(next());
7762ec34544SRui Ueyama   expect(")");
777b579c439SRui Ueyama 
7782ec34544SRui Ueyama   return [=] {
7793837f427SRui Ueyama     if (!e().getValue())
7802682bc3cSFangrui Song       errorOrWarn(msg);
7813837f427SRui Ueyama     return script->getDot();
7822ec34544SRui Ueyama   };
7832ec34544SRui Ueyama }
7842ec34544SRui Ueyama 
785a46d08ebSGeorge Rimar // Tries to read the special directive for an output section definition which
786a46d08ebSGeorge Rimar // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
787a46d08ebSGeorge Rimar // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
7883837f427SRui Ueyama bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) {
7893837f427SRui Ueyama   if (tok1 != "(")
790a46d08ebSGeorge Rimar     return false;
7913837f427SRui Ueyama   if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" && tok2 != "OVERLAY")
792a46d08ebSGeorge Rimar     return false;
793a46d08ebSGeorge Rimar 
794a46d08ebSGeorge Rimar   expect("(");
795a46d08ebSGeorge Rimar   if (consume("NOLOAD")) {
7963837f427SRui Ueyama     cmd->noload = true;
797fdc41aa2SMatt Schulte     cmd->type = SHT_NOBITS;
798a46d08ebSGeorge Rimar   } else {
799a46d08ebSGeorge Rimar     skip(); // This is "COPY", "INFO" or "OVERLAY".
8003837f427SRui Ueyama     cmd->nonAlloc = true;
801a46d08ebSGeorge Rimar   }
802a46d08ebSGeorge Rimar   expect(")");
803a46d08ebSGeorge Rimar   return true;
804a46d08ebSGeorge Rimar }
805a46d08ebSGeorge Rimar 
8061c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output
8071c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)",
8081c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)".
8093271d370SRui Ueyama //
8103271d370SRui Ueyama // An output section name can be followed by an address expression
8111c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be
81297f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning
8131c08e9f5SGeorge Rimar // of directive.
8143271d370SRui Ueyama //
815b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
816fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
8173837f427SRui Ueyama void ScriptParser::readSectionAddressType(OutputSection *cmd) {
8183837f427SRui Ueyama   if (readSectionDirective(cmd, peek(), peek2()))
8193271d370SRui Ueyama     return;
8203271d370SRui Ueyama 
8213837f427SRui Ueyama   cmd->addrExpr = readExpr();
8223837f427SRui Ueyama   if (peek() == "(" && !readSectionDirective(cmd, "(", peek2()))
823a46d08ebSGeorge Rimar     setError("unknown section directive: " + peek2());
824fbb0463fSGeorge Rimar }
825fbb0463fSGeorge Rimar 
8263837f427SRui Ueyama static Expr checkAlignment(Expr e, std::string &loc) {
827f22ec9ddSGeorge Rimar   return [=] {
8283837f427SRui Ueyama     uint64_t alignment = std::max((uint64_t)1, e().getValue());
8293837f427SRui Ueyama     if (!isPowerOf2_64(alignment)) {
8303837f427SRui Ueyama       error(loc + ": alignment must be power of 2");
831f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
832f22ec9ddSGeorge Rimar     }
8333837f427SRui Ueyama     return alignment;
834f22ec9ddSGeorge Rimar   };
835f22ec9ddSGeorge Rimar }
836f22ec9ddSGeorge Rimar 
837a582419aSGeorge Rimar OutputSection *ScriptParser::readOverlaySectionDescription() {
8383837f427SRui Ueyama   OutputSection *cmd =
8393837f427SRui Ueyama       script->createOutputSection(next(), getCurrentLocation());
8403837f427SRui Ueyama   cmd->inOverlay = true;
841a582419aSGeorge Rimar   expect("{");
842dbd0ad33SPeter Smith   while (!errorCount() && !consume("}")) {
843dbd0ad33SPeter Smith     uint64_t withFlags = 0;
844dbd0ad33SPeter Smith     uint64_t withoutFlags = 0;
845dbd0ad33SPeter Smith     if (consume("INPUT_SECTION_FLAGS"))
846dbd0ad33SPeter Smith       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
847dbd0ad33SPeter Smith     cmd->sectionCommands.push_back(
848dbd0ad33SPeter Smith         readInputSectionRules(next(), withFlags, withoutFlags));
849dbd0ad33SPeter Smith   }
8503837f427SRui Ueyama   return cmd;
851a582419aSGeorge Rimar }
852a582419aSGeorge Rimar 
8533837f427SRui Ueyama OutputSection *ScriptParser::readOutputSectionDescription(StringRef outSec) {
8543837f427SRui Ueyama   OutputSection *cmd =
8553837f427SRui Ueyama       script->createOutputSection(outSec, getCurrentLocation());
8563271d370SRui Ueyama 
8573837f427SRui Ueyama   size_t symbolsReferenced = script->referencedSymbols.size();
858c4df670dSGeorge Rimar 
8593271d370SRui Ueyama   if (peek() != ":")
8603837f427SRui Ueyama     readSectionAddressType(cmd);
8612ec34544SRui Ueyama   expect(":");
8622ec34544SRui Ueyama 
8633837f427SRui Ueyama   std::string location = getCurrentLocation();
8642ec34544SRui Ueyama   if (consume("AT"))
8653837f427SRui Ueyama     cmd->lmaExpr = readParenExpr();
8662ec34544SRui Ueyama   if (consume("ALIGN"))
8673837f427SRui Ueyama     cmd->alignExpr = checkAlignment(readParenExpr(), location);
8682ec34544SRui Ueyama   if (consume("SUBALIGN"))
8693837f427SRui Ueyama     cmd->subalignExpr = checkAlignment(readParenExpr(), location);
8702ec34544SRui Ueyama 
8712ec34544SRui Ueyama   // Parse constraints.
8722ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
8733837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadOnly;
8742ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
8753837f427SRui Ueyama     cmd->constraint = ConstraintKind::ReadWrite;
8762ec34544SRui Ueyama   expect("{");
8772ec34544SRui Ueyama 
878b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
8793837f427SRui Ueyama     StringRef tok = next();
8803837f427SRui Ueyama     if (tok == ";") {
8812ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
8823837f427SRui Ueyama     } else if (SymbolAssignment *assign = readAssignment(tok)) {
8833837f427SRui Ueyama       cmd->sectionCommands.push_back(assign);
8843837f427SRui Ueyama     } else if (ByteCommand *data = readByteCommand(tok)) {
8853837f427SRui Ueyama       cmd->sectionCommands.push_back(data);
8863837f427SRui Ueyama     } else if (tok == "CONSTRUCTORS") {
8872ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
8882ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
8892ec34544SRui Ueyama       // For ELF, we should ignore.
8903837f427SRui Ueyama     } else if (tok == "FILL") {
8910810f16fSGeorge Rimar       // We handle the FILL command as an alias for =fillexp section attribute,
8920810f16fSGeorge Rimar       // which is different from what GNU linkers do.
8930810f16fSGeorge Rimar       // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
894bb7d2b17SGeorgii Rymar       if (peek() != "(")
895bb7d2b17SGeorgii Rymar         setError("( expected, but got " + peek());
8963837f427SRui Ueyama       cmd->filler = readFill();
8973837f427SRui Ueyama     } else if (tok == "SORT") {
8982ec34544SRui Ueyama       readSort();
8993837f427SRui Ueyama     } else if (tok == "INCLUDE") {
9002e9d40d5SRui Ueyama       readInclude();
9012ec34544SRui Ueyama     } else if (peek() == "(") {
9023837f427SRui Ueyama       cmd->sectionCommands.push_back(readInputSectionDescription(tok));
9032ec34544SRui Ueyama     } else {
904f49fe218SGeorge Rimar       // We have a file name and no input sections description. It is not a
905f49fe218SGeorge Rimar       // commonly used syntax, but still acceptable. In that case, all sections
906f49fe218SGeorge Rimar       // from the file will be included.
907dbd0ad33SPeter Smith       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
908dbd0ad33SPeter Smith       // handle this case here as it will already have been matched by the
909dbd0ad33SPeter Smith       // case above.
9103837f427SRui Ueyama       auto *isd = make<InputSectionDescription>(tok);
911c42fe247SThomas Preud'homme       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
9123837f427SRui Ueyama       cmd->sectionCommands.push_back(isd);
9132ec34544SRui Ueyama     }
9142ec34544SRui Ueyama   }
9152ec34544SRui Ueyama 
9162ec34544SRui Ueyama   if (consume(">"))
917adcd0268SBenjamin Kramer     cmd->memoryRegionName = std::string(next());
9182ec34544SRui Ueyama 
9195d01a8beSGeorge Rimar   if (consume("AT")) {
9205d01a8beSGeorge Rimar     expect(">");
921adcd0268SBenjamin Kramer     cmd->lmaRegionName = std::string(next());
9225d01a8beSGeorge Rimar   }
9235d01a8beSGeorge Rimar 
9243837f427SRui Ueyama   if (cmd->lmaExpr && !cmd->lmaRegionName.empty())
9255d01a8beSGeorge Rimar     error("section can't have both LMA and a load region");
9265d01a8beSGeorge Rimar 
9273837f427SRui Ueyama   cmd->phdrs = readOutputSectionPhdrs();
9282ec34544SRui Ueyama 
9290810f16fSGeorge Rimar   if (peek() == "=" || peek().startswith("=")) {
9303837f427SRui Ueyama     inExpr = true;
9310810f16fSGeorge Rimar     consume("=");
9323837f427SRui Ueyama     cmd->filler = readFill();
9333837f427SRui Ueyama     inExpr = false;
9340810f16fSGeorge Rimar   }
9352ec34544SRui Ueyama 
9362ec34544SRui Ueyama   // Consume optional comma following output section command.
9372ec34544SRui Ueyama   consume(",");
9382ec34544SRui Ueyama 
9393837f427SRui Ueyama   if (script->referencedSymbols.size() > symbolsReferenced)
9403837f427SRui Ueyama     cmd->expressionsUseSymbols = true;
9413837f427SRui Ueyama   return cmd;
9422ec34544SRui Ueyama }
9432ec34544SRui Ueyama 
9440810f16fSGeorge Rimar // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
9452ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
9460810f16fSGeorge Rimar // We do not support using symbols in such expressions.
9472ec34544SRui Ueyama //
9488acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
9498acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
9508acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
951bb7d2b17SGeorgii Rymar // Also, we require that expressions with operators must be wrapped into
952bb7d2b17SGeorgii Rymar // round brackets. We did it to resolve the ambiguity when parsing scripts like:
953bb7d2b17SGeorgii Rymar // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
9540810f16fSGeorge Rimar std::array<uint8_t, 4> ScriptParser::readFill() {
955bb7d2b17SGeorgii Rymar   uint64_t value = readPrimary()().val;
9563837f427SRui Ueyama   if (value > UINT32_MAX)
9570810f16fSGeorge Rimar     setError("filler expression result does not fit 32-bit: 0x" +
9583837f427SRui Ueyama              Twine::utohexstr(value));
959b58079d4SRui Ueyama 
9603837f427SRui Ueyama   std::array<uint8_t, 4> buf;
9613837f427SRui Ueyama   write32be(buf.data(), (uint32_t)value);
9623837f427SRui Ueyama   return buf;
9632ec34544SRui Ueyama }
9642ec34544SRui Ueyama 
9653837f427SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
9662ec34544SRui Ueyama   expect("(");
9673837f427SRui Ueyama   SymbolAssignment *cmd = readSymbolAssignment(next());
9683837f427SRui Ueyama   cmd->provide = provide;
9693837f427SRui Ueyama   cmd->hidden = hidden;
9702ec34544SRui Ueyama   expect(")");
9713837f427SRui Ueyama   return cmd;
9722ec34544SRui Ueyama }
9732ec34544SRui Ueyama 
9743837f427SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
975d30a78b3SGeorge Rimar   // Assert expression returns Dot, so this is equal to ".=."
9763837f427SRui Ueyama   if (tok == "ASSERT")
977d30a78b3SGeorge Rimar     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
978d30a78b3SGeorge Rimar 
9793837f427SRui Ueyama   size_t oldPos = pos;
9803837f427SRui Ueyama   SymbolAssignment *cmd = nullptr;
981e88b76a9SGeorge Rimar   if (peek() == "=" || peek() == "+=")
9823837f427SRui Ueyama     cmd = readSymbolAssignment(tok);
9833837f427SRui Ueyama   else if (tok == "PROVIDE")
9843837f427SRui Ueyama     cmd = readProvideHidden(true, false);
9853837f427SRui Ueyama   else if (tok == "HIDDEN")
9863837f427SRui Ueyama     cmd = readProvideHidden(false, true);
9873837f427SRui Ueyama   else if (tok == "PROVIDE_HIDDEN")
9883837f427SRui Ueyama     cmd = readProvideHidden(true, true);
989e88b76a9SGeorge Rimar 
9903837f427SRui Ueyama   if (cmd) {
9913837f427SRui Ueyama     cmd->commandString =
9923837f427SRui Ueyama         tok.str() + " " +
9933837f427SRui Ueyama         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
994e88b76a9SGeorge Rimar     expect(";");
9952ec34544SRui Ueyama   }
9963837f427SRui Ueyama   return cmd;
9972ec34544SRui Ueyama }
9982ec34544SRui Ueyama 
9993837f427SRui Ueyama SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
10003837f427SRui Ueyama   StringRef op = next();
10013837f427SRui Ueyama   assert(op == "=" || op == "+=");
10023837f427SRui Ueyama   Expr e = readExpr();
10033837f427SRui Ueyama   if (op == "+=") {
10043837f427SRui Ueyama     std::string loc = getCurrentLocation();
10053837f427SRui Ueyama     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
10062ec34544SRui Ueyama   }
10073837f427SRui Ueyama   return make<SymbolAssignment>(name, e, getCurrentLocation());
10082ec34544SRui Ueyama }
10092ec34544SRui Ueyama 
10102ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
10112ec34544SRui Ueyama // script expression.
10122ec34544SRui Ueyama Expr ScriptParser::readExpr() {
10132ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
10142ec34544SRui Ueyama   // they apply different tokenization rules.
10153837f427SRui Ueyama   bool orig = inExpr;
10163837f427SRui Ueyama   inExpr = true;
10173837f427SRui Ueyama   Expr e = readExpr1(readPrimary(), 0);
10183837f427SRui Ueyama   inExpr = orig;
10193837f427SRui Ueyama   return e;
10202ec34544SRui Ueyama }
10212ec34544SRui Ueyama 
10223837f427SRui Ueyama Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
10233837f427SRui Ueyama   if (op == "+")
10243837f427SRui Ueyama     return [=] { return add(l(), r()); };
10253837f427SRui Ueyama   if (op == "-")
10263837f427SRui Ueyama     return [=] { return sub(l(), r()); };
10273837f427SRui Ueyama   if (op == "*")
10283837f427SRui Ueyama     return [=] { return l().getValue() * r().getValue(); };
10293837f427SRui Ueyama   if (op == "/") {
10303837f427SRui Ueyama     std::string loc = getCurrentLocation();
10317b91e213SGeorge Rimar     return [=]() -> uint64_t {
10323837f427SRui Ueyama       if (uint64_t rv = r().getValue())
10333837f427SRui Ueyama         return l().getValue() / rv;
10343837f427SRui Ueyama       error(loc + ": division by zero");
1035067617f9SRui Ueyama       return 0;
10367b91e213SGeorge Rimar     };
10377b91e213SGeorge Rimar   }
10383837f427SRui Ueyama   if (op == "%") {
10393837f427SRui Ueyama     std::string loc = getCurrentLocation();
10407b91e213SGeorge Rimar     return [=]() -> uint64_t {
10413837f427SRui Ueyama       if (uint64_t rv = r().getValue())
10423837f427SRui Ueyama         return l().getValue() % rv;
10433837f427SRui Ueyama       error(loc + ": modulo by zero");
1044067617f9SRui Ueyama       return 0;
10457b91e213SGeorge Rimar     };
10467b91e213SGeorge Rimar   }
10473837f427SRui Ueyama   if (op == "<<")
10483837f427SRui Ueyama     return [=] { return l().getValue() << r().getValue(); };
10493837f427SRui Ueyama   if (op == ">>")
10503837f427SRui Ueyama     return [=] { return l().getValue() >> r().getValue(); };
10513837f427SRui Ueyama   if (op == "<")
10523837f427SRui Ueyama     return [=] { return l().getValue() < r().getValue(); };
10533837f427SRui Ueyama   if (op == ">")
10543837f427SRui Ueyama     return [=] { return l().getValue() > r().getValue(); };
10553837f427SRui Ueyama   if (op == ">=")
10563837f427SRui Ueyama     return [=] { return l().getValue() >= r().getValue(); };
10573837f427SRui Ueyama   if (op == "<=")
10583837f427SRui Ueyama     return [=] { return l().getValue() <= r().getValue(); };
10593837f427SRui Ueyama   if (op == "==")
10603837f427SRui Ueyama     return [=] { return l().getValue() == r().getValue(); };
10613837f427SRui Ueyama   if (op == "!=")
10623837f427SRui Ueyama     return [=] { return l().getValue() != r().getValue(); };
10633837f427SRui Ueyama   if (op == "||")
10643837f427SRui Ueyama     return [=] { return l().getValue() || r().getValue(); };
10653837f427SRui Ueyama   if (op == "&&")
10663837f427SRui Ueyama     return [=] { return l().getValue() && r().getValue(); };
10673837f427SRui Ueyama   if (op == "&")
10683837f427SRui Ueyama     return [=] { return bitAnd(l(), r()); };
10693837f427SRui Ueyama   if (op == "|")
10703837f427SRui Ueyama     return [=] { return bitOr(l(), r()); };
10712ec34544SRui Ueyama   llvm_unreachable("invalid operator");
10722ec34544SRui Ueyama }
10732ec34544SRui Ueyama 
10742ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
10752ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
10763837f427SRui Ueyama Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1077b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
10782ec34544SRui Ueyama     // Read an operator and an expression.
10792ec34544SRui Ueyama     if (consume("?"))
10803837f427SRui Ueyama       return readTernary(lhs);
10813837f427SRui Ueyama     StringRef op1 = peek();
10823837f427SRui Ueyama     if (precedence(op1) < minPrec)
10832ec34544SRui Ueyama       break;
10842ec34544SRui Ueyama     skip();
10853837f427SRui Ueyama     Expr rhs = readPrimary();
10862ec34544SRui Ueyama 
10872ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
10882ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
10892ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
10902ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
10912ec34544SRui Ueyama     while (!atEOF()) {
10923837f427SRui Ueyama       StringRef op2 = peek();
10933837f427SRui Ueyama       if (precedence(op2) <= precedence(op1))
10942ec34544SRui Ueyama         break;
10953837f427SRui Ueyama       rhs = readExpr1(rhs, precedence(op2));
10962ec34544SRui Ueyama     }
10972ec34544SRui Ueyama 
10983837f427SRui Ueyama     lhs = combine(op1, lhs, rhs);
10992ec34544SRui Ueyama   }
11003837f427SRui Ueyama   return lhs;
11012ec34544SRui Ueyama }
11022ec34544SRui Ueyama 
11035fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
11043837f427SRui Ueyama   std::string location = getCurrentLocation();
11055fb17128SGeorge Rimar   return [=]() -> uint64_t {
11063837f427SRui Ueyama     if (target)
11073837f427SRui Ueyama       return config->commonPageSize;
11083837f427SRui Ueyama     error(location + ": unable to calculate page size");
11095fb17128SGeorge Rimar     return 4096; // Return a dummy value.
11105fb17128SGeorge Rimar   };
11115fb17128SGeorge Rimar }
11125fb17128SGeorge Rimar 
11135fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
11143837f427SRui Ueyama   StringRef s = readParenLiteral();
11153837f427SRui Ueyama   if (s == "COMMONPAGESIZE")
11165fb17128SGeorge Rimar     return getPageSize();
11173837f427SRui Ueyama   if (s == "MAXPAGESIZE")
11183837f427SRui Ueyama     return [] { return config->maxPageSize; };
11193837f427SRui Ueyama   setError("unknown constant: " + s);
1120b068b037SGeorge Rimar   return [] { return 0; };
11212ec34544SRui Ueyama }
11222ec34544SRui Ueyama 
11235c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
11245c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
11255c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
11263837f427SRui Ueyama static Optional<uint64_t> parseInt(StringRef tok) {
11272ec34544SRui Ueyama   // Hexadecimal
11283837f427SRui Ueyama   uint64_t val;
11293837f427SRui Ueyama   if (tok.startswith_lower("0x")) {
11303837f427SRui Ueyama     if (!to_integer(tok.substr(2), val, 16))
11314092016bSRui Ueyama       return None;
11323837f427SRui Ueyama     return val;
11334092016bSRui Ueyama   }
11343837f427SRui Ueyama   if (tok.endswith_lower("H")) {
11353837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 16))
11364092016bSRui Ueyama       return None;
11373837f427SRui Ueyama     return val;
11384092016bSRui Ueyama   }
11392ec34544SRui Ueyama 
11402ec34544SRui Ueyama   // Decimal
11413837f427SRui Ueyama   if (tok.endswith_lower("K")) {
11423837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
11435c65088fSRui Ueyama       return None;
11443837f427SRui Ueyama     return val * 1024;
11452ec34544SRui Ueyama   }
11463837f427SRui Ueyama   if (tok.endswith_lower("M")) {
11473837f427SRui Ueyama     if (!to_integer(tok.drop_back(), val, 10))
11485c65088fSRui Ueyama       return None;
11493837f427SRui Ueyama     return val * 1024 * 1024;
11505c65088fSRui Ueyama   }
11513837f427SRui Ueyama   if (!to_integer(tok, val, 10))
11525c65088fSRui Ueyama     return None;
11533837f427SRui Ueyama   return val;
11542ec34544SRui Ueyama }
11552ec34544SRui Ueyama 
11563837f427SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
11573837f427SRui Ueyama   int size = StringSwitch<int>(tok)
11582ec34544SRui Ueyama                  .Case("BYTE", 1)
11592ec34544SRui Ueyama                  .Case("SHORT", 2)
11602ec34544SRui Ueyama                  .Case("LONG", 4)
11612ec34544SRui Ueyama                  .Case("QUAD", 8)
11622ec34544SRui Ueyama                  .Default(-1);
11633837f427SRui Ueyama   if (size == -1)
11642ec34544SRui Ueyama     return nullptr;
116584bcabcbSGeorge Rimar 
11663837f427SRui Ueyama   size_t oldPos = pos;
11673837f427SRui Ueyama   Expr e = readParenExpr();
11683837f427SRui Ueyama   std::string commandString =
11693837f427SRui Ueyama       tok.str() + " " +
11703837f427SRui Ueyama       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
11713837f427SRui Ueyama   return make<ByteCommand>(e, size, commandString);
11722ec34544SRui Ueyama }
11732ec34544SRui Ueyama 
1174dbd0ad33SPeter Smith static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1175dbd0ad33SPeter Smith   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1176dbd0ad33SPeter Smith     return asInt;
1177dbd0ad33SPeter Smith #define CASE_ENT(enum) #enum, ELF::enum
1178dbd0ad33SPeter Smith   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1179dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_WRITE))
1180dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ALLOC))
1181dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXECINSTR))
1182dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_MERGE))
1183dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_STRINGS))
1184dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_INFO_LINK))
1185dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_LINK_ORDER))
1186dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1187dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_GROUP))
1188dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_TLS))
1189dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_COMPRESSED))
1190dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_EXCLUDE))
1191dbd0ad33SPeter Smith       .Case(CASE_ENT(SHF_ARM_PURECODE))
1192dbd0ad33SPeter Smith       .Default(None);
1193dbd0ad33SPeter Smith #undef CASE_ENT
1194dbd0ad33SPeter Smith }
1195dbd0ad33SPeter Smith 
1196dbd0ad33SPeter Smith // Reads the '(' <flags> ')' list of section flags in
1197dbd0ad33SPeter Smith // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1198dbd0ad33SPeter Smith // following form:
1199dbd0ad33SPeter Smith // <flags> ::= <flag>
1200dbd0ad33SPeter Smith //           | <flags> & flag
1201dbd0ad33SPeter Smith // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1202dbd0ad33SPeter Smith // If the first character of <flag> is a ! then this means without flag,
1203dbd0ad33SPeter Smith // otherwise with flag.
1204dbd0ad33SPeter Smith // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1205dbd0ad33SPeter Smith // without flag SHF_WRITE.
1206dbd0ad33SPeter Smith std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1207dbd0ad33SPeter Smith    uint64_t withFlags = 0;
1208dbd0ad33SPeter Smith    uint64_t withoutFlags = 0;
1209dbd0ad33SPeter Smith    expect("(");
1210dbd0ad33SPeter Smith    while (!errorCount()) {
1211dbd0ad33SPeter Smith     StringRef tok = unquote(next());
1212dbd0ad33SPeter Smith     bool without = tok.consume_front("!");
1213dbd0ad33SPeter Smith     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1214dbd0ad33SPeter Smith       if (without)
1215dbd0ad33SPeter Smith         withoutFlags |= *flag;
1216dbd0ad33SPeter Smith       else
1217dbd0ad33SPeter Smith         withFlags |= *flag;
1218dbd0ad33SPeter Smith     } else {
1219dbd0ad33SPeter Smith       setError("unrecognised flag: " + tok);
1220dbd0ad33SPeter Smith     }
1221dbd0ad33SPeter Smith     if (consume(")"))
1222dbd0ad33SPeter Smith       break;
1223dbd0ad33SPeter Smith     if (!consume("&")) {
1224dbd0ad33SPeter Smith       next();
1225dbd0ad33SPeter Smith       setError("expected & or )");
1226dbd0ad33SPeter Smith     }
1227dbd0ad33SPeter Smith   }
1228dbd0ad33SPeter Smith   return std::make_pair(withFlags, withoutFlags);
1229dbd0ad33SPeter Smith }
1230dbd0ad33SPeter Smith 
12312ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
12322ec34544SRui Ueyama   expect("(");
12333837f427SRui Ueyama   bool orig = inExpr;
12343837f427SRui Ueyama   inExpr = false;
12353837f427SRui Ueyama   StringRef tok = next();
12363837f427SRui Ueyama   inExpr = orig;
12372ec34544SRui Ueyama   expect(")");
12383837f427SRui Ueyama   return tok;
12392ec34544SRui Ueyama }
12402ec34544SRui Ueyama 
12413837f427SRui Ueyama static void checkIfExists(OutputSection *cmd, StringRef location) {
12423837f427SRui Ueyama   if (cmd->location.empty() && script->errorOnMissingSection)
12433837f427SRui Ueyama     error(location + ": undefined section " + cmd->name);
124405c4f67cSRafael Espindola }
124505c4f67cSRafael Espindola 
1246e4f385d8SFangrui Song static bool isValidSymbolName(StringRef s) {
1247e4f385d8SFangrui Song   auto valid = [](char c) {
1248e4f385d8SFangrui Song     return isAlnum(c) || c == '$' || c == '.' || c == '_';
1249e4f385d8SFangrui Song   };
1250e4f385d8SFangrui Song   return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1251e4f385d8SFangrui Song }
1252e4f385d8SFangrui Song 
12532ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
12542ec34544SRui Ueyama   if (peek() == "(")
12552ec34544SRui Ueyama     return readParenExpr();
12562ec34544SRui Ueyama 
12575c65088fSRui Ueyama   if (consume("~")) {
12583837f427SRui Ueyama     Expr e = readPrimary();
12593837f427SRui Ueyama     return [=] { return ~e().getValue(); };
12602ec34544SRui Ueyama   }
12616f1d954eSHafiz Abid Qadeer   if (consume("!")) {
12623837f427SRui Ueyama     Expr e = readPrimary();
12633837f427SRui Ueyama     return [=] { return !e().getValue(); };
12646f1d954eSHafiz Abid Qadeer   }
12655c65088fSRui Ueyama   if (consume("-")) {
12663837f427SRui Ueyama     Expr e = readPrimary();
12673837f427SRui Ueyama     return [=] { return -e().getValue(); };
12682ec34544SRui Ueyama   }
12692ec34544SRui Ueyama 
12703837f427SRui Ueyama   StringRef tok = next();
12713837f427SRui Ueyama   std::string location = getCurrentLocation();
12725c65088fSRui Ueyama 
12732ec34544SRui Ueyama   // Built-in functions are parsed here.
12742ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
12753837f427SRui Ueyama   if (tok == "ABSOLUTE") {
12763837f427SRui Ueyama     Expr inner = readParenExpr();
12772ec34544SRui Ueyama     return [=] {
12783837f427SRui Ueyama       ExprValue i = inner();
12793837f427SRui Ueyama       i.forceAbsolute = true;
12803837f427SRui Ueyama       return i;
12812ec34544SRui Ueyama     };
12822ec34544SRui Ueyama   }
12833837f427SRui Ueyama   if (tok == "ADDR") {
12843837f427SRui Ueyama     StringRef name = readParenLiteral();
12853837f427SRui Ueyama     OutputSection *sec = script->getOrCreateOutputSection(name);
12863837f427SRui Ueyama     sec->usedInExpression = true;
128741c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
12883837f427SRui Ueyama       checkIfExists(sec, location);
12893837f427SRui Ueyama       return {sec, false, 0, location};
129041c7ab4aSGeorge Rimar     };
12912ec34544SRui Ueyama   }
12923837f427SRui Ueyama   if (tok == "ALIGN") {
12932ec34544SRui Ueyama     expect("(");
12943837f427SRui Ueyama     Expr e = readExpr();
1295f22ec9ddSGeorge Rimar     if (consume(")")) {
12963837f427SRui Ueyama       e = checkAlignment(e, location);
12973837f427SRui Ueyama       return [=] { return alignTo(script->getDot(), e().getValue()); };
1298f22ec9ddSGeorge Rimar     }
1299b579c439SRui Ueyama     expect(",");
13003837f427SRui Ueyama     Expr e2 = checkAlignment(readExpr(), location);
13012ec34544SRui Ueyama     expect(")");
13023c6de1a6SPetr Hosek     return [=] {
13033837f427SRui Ueyama       ExprValue v = e();
13043837f427SRui Ueyama       v.alignment = e2().getValue();
13053837f427SRui Ueyama       return v;
13063c6de1a6SPetr Hosek     };
13072ec34544SRui Ueyama   }
13083837f427SRui Ueyama   if (tok == "ALIGNOF") {
13093837f427SRui Ueyama     StringRef name = readParenLiteral();
13103837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
1311617e2f98SRui Ueyama     return [=] {
13123837f427SRui Ueyama       checkIfExists(cmd, location);
13133837f427SRui Ueyama       return cmd->alignment;
1314617e2f98SRui Ueyama     };
13152ec34544SRui Ueyama   }
13163837f427SRui Ueyama   if (tok == "ASSERT")
1317d30a78b3SGeorge Rimar     return readAssert();
13183837f427SRui Ueyama   if (tok == "CONSTANT")
13195fb17128SGeorge Rimar     return readConstant();
13203837f427SRui Ueyama   if (tok == "DATA_SEGMENT_ALIGN") {
13212ec34544SRui Ueyama     expect("(");
13223837f427SRui Ueyama     Expr e = readExpr();
13232ec34544SRui Ueyama     expect(",");
13242ec34544SRui Ueyama     readExpr();
13252ec34544SRui Ueyama     expect(")");
132660833f6eSGeorge Rimar     return [=] {
13273837f427SRui Ueyama       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
132860833f6eSGeorge Rimar     };
13292ec34544SRui Ueyama   }
13303837f427SRui Ueyama   if (tok == "DATA_SEGMENT_END") {
13312ec34544SRui Ueyama     expect("(");
13322ec34544SRui Ueyama     expect(".");
13332ec34544SRui Ueyama     expect(")");
13343837f427SRui Ueyama     return [] { return script->getDot(); };
13352ec34544SRui Ueyama   }
13363837f427SRui Ueyama   if (tok == "DATA_SEGMENT_RELRO_END") {
13372ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
13382ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
13392ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
13402ec34544SRui Ueyama     expect("(");
13412ec34544SRui Ueyama     readExpr();
13422ec34544SRui Ueyama     expect(",");
13432ec34544SRui Ueyama     readExpr();
13442ec34544SRui Ueyama     expect(")");
13453837f427SRui Ueyama     Expr e = getPageSize();
13463837f427SRui Ueyama     return [=] { return alignTo(script->getDot(), e().getValue()); };
13472ec34544SRui Ueyama   }
13483837f427SRui Ueyama   if (tok == "DEFINED") {
13493837f427SRui Ueyama     StringRef name = readParenLiteral();
13501f166edeSHafiz Abid Qadeer     return [=] {
13511f166edeSHafiz Abid Qadeer       Symbol *b = symtab->find(name);
13521f166edeSHafiz Abid Qadeer       return (b && b->isDefined()) ? 1 : 0;
13531f166edeSHafiz Abid Qadeer     };
13542ec34544SRui Ueyama   }
13553837f427SRui Ueyama   if (tok == "LENGTH") {
13563837f427SRui Ueyama     StringRef name = readParenLiteral();
13573837f427SRui Ueyama     if (script->memoryRegions.count(name) == 0) {
13583837f427SRui Ueyama       setError("memory region not defined: " + name);
1359b068b037SGeorge Rimar       return [] { return 0; };
1360b068b037SGeorge Rimar     }
136192b5b980SFangrui Song     return script->memoryRegions[name]->length;
136291b95b61SRui Ueyama   }
13633837f427SRui Ueyama   if (tok == "LOADADDR") {
13643837f427SRui Ueyama     StringRef name = readParenLiteral();
13653837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
13663837f427SRui Ueyama     cmd->usedInExpression = true;
1367617e2f98SRui Ueyama     return [=] {
13683837f427SRui Ueyama       checkIfExists(cmd, location);
13693837f427SRui Ueyama       return cmd->getLMA();
1370617e2f98SRui Ueyama     };
13712ec34544SRui Ueyama   }
1372fa1145a8SIsaac Richter   if (tok == "LOG2CEIL") {
1373fa1145a8SIsaac Richter     expect("(");
1374fa1145a8SIsaac Richter     Expr a = readExpr();
1375fa1145a8SIsaac Richter     expect(")");
1376fa1145a8SIsaac Richter     return [=] {
1377fa1145a8SIsaac Richter       // LOG2CEIL(0) is defined to be 0.
1378fa1145a8SIsaac Richter       return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1379fa1145a8SIsaac Richter     };
1380fa1145a8SIsaac Richter   }
13813837f427SRui Ueyama   if (tok == "MAX" || tok == "MIN") {
1382fd11560fSGeorge Rimar     expect("(");
13833837f427SRui Ueyama     Expr a = readExpr();
1384fd11560fSGeorge Rimar     expect(",");
13853837f427SRui Ueyama     Expr b = readExpr();
1386fd11560fSGeorge Rimar     expect(")");
13873837f427SRui Ueyama     if (tok == "MIN")
13883837f427SRui Ueyama       return [=] { return std::min(a().getValue(), b().getValue()); };
13893837f427SRui Ueyama     return [=] { return std::max(a().getValue(), b().getValue()); };
1390fd11560fSGeorge Rimar   }
13913837f427SRui Ueyama   if (tok == "ORIGIN") {
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]->origin;
139891b95b61SRui Ueyama   }
13993837f427SRui Ueyama   if (tok == "SEGMENT_START") {
14002ec34544SRui Ueyama     expect("(");
14012ec34544SRui Ueyama     skip();
14022ec34544SRui Ueyama     expect(",");
14033837f427SRui Ueyama     Expr e = readExpr();
14042ec34544SRui Ueyama     expect(")");
14053837f427SRui Ueyama     return [=] { return e(); };
14062ec34544SRui Ueyama   }
14073837f427SRui Ueyama   if (tok == "SIZEOF") {
14083837f427SRui Ueyama     StringRef name = readParenLiteral();
14093837f427SRui Ueyama     OutputSection *cmd = script->getOrCreateOutputSection(name);
141005c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
141105c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
141205c4f67cSRafael Espindola     // be empty.
14133837f427SRui Ueyama     return [=] { return cmd->size; };
14142ec34544SRui Ueyama   }
14153837f427SRui Ueyama   if (tok == "SIZEOF_HEADERS")
141607837b8fSFangrui Song     return [=] { return elf::getHeaderSize(); };
14172ec34544SRui Ueyama 
14184eb2eccbSRui Ueyama   // Tok is the dot.
14193837f427SRui Ueyama   if (tok == ".")
14203837f427SRui Ueyama     return [=] { return script->getSymbolValue(tok, location); };
14214eb2eccbSRui Ueyama 
14222ec34544SRui Ueyama   // Tok is a literal number.
14233837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
14243837f427SRui Ueyama     return [=] { return *val; };
14252ec34544SRui Ueyama 
14262ec34544SRui Ueyama   // Tok is a symbol name.
1427e4f385d8SFangrui Song   if (!isValidSymbolName(tok))
14283837f427SRui Ueyama     setError("malformed number: " + tok);
14293837f427SRui Ueyama   script->referencedSymbols.push_back(tok);
14303837f427SRui Ueyama   return [=] { return script->getSymbolValue(tok, location); };
14312ec34544SRui Ueyama }
14322ec34544SRui Ueyama 
14333837f427SRui Ueyama Expr ScriptParser::readTernary(Expr cond) {
14343837f427SRui Ueyama   Expr l = readExpr();
14352ec34544SRui Ueyama   expect(":");
14363837f427SRui Ueyama   Expr r = readExpr();
14373837f427SRui Ueyama   return [=] { return cond().getValue() ? l() : r(); };
14382ec34544SRui Ueyama }
14392ec34544SRui Ueyama 
14402ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
14412ec34544SRui Ueyama   expect("(");
14423837f427SRui Ueyama   Expr e = readExpr();
14432ec34544SRui Ueyama   expect(")");
14443837f427SRui Ueyama   return e;
14452ec34544SRui Ueyama }
14462ec34544SRui Ueyama 
14472ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
14483837f427SRui Ueyama   std::vector<StringRef> phdrs;
1449b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
14503837f427SRui Ueyama     StringRef tok = next();
14513837f427SRui Ueyama     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
14522ec34544SRui Ueyama   }
14533837f427SRui Ueyama   return phdrs;
14542ec34544SRui Ueyama }
14552ec34544SRui Ueyama 
14562ec34544SRui Ueyama // Read a program header type name. The next token must be a
14572ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
14582ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
14593837f427SRui Ueyama   StringRef tok = next();
14603837f427SRui Ueyama   if (Optional<uint64_t> val = parseInt(tok))
14613837f427SRui Ueyama     return *val;
14622ec34544SRui Ueyama 
14633837f427SRui Ueyama   unsigned ret = StringSwitch<unsigned>(tok)
14642ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
14652ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
14662ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
14672ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
14682ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
14692ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
14702ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
14712ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
14722ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
14732ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
14742ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
14752ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
14762ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
14772ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
14782ec34544SRui Ueyama                      .Default(-1);
14792ec34544SRui Ueyama 
14803837f427SRui Ueyama   if (ret == (unsigned)-1) {
14813837f427SRui Ueyama     setError("invalid program header type: " + tok);
14822ec34544SRui Ueyama     return PT_NULL;
14832ec34544SRui Ueyama   }
14843837f427SRui Ueyama   return ret;
14852ec34544SRui Ueyama }
14862ec34544SRui Ueyama 
14872ec34544SRui Ueyama // Reads an anonymous version declaration.
14882ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
14893837f427SRui Ueyama   std::vector<SymbolVersion> locals;
14903837f427SRui Ueyama   std::vector<SymbolVersion> globals;
14913837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
1492e28a70daSFangrui Song   for (const SymbolVersion &pat : locals)
1493e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
1494e28a70daSFangrui Song   for (const SymbolVersion &pat : globals)
1495e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(pat);
14962ec34544SRui Ueyama 
14972ec34544SRui Ueyama   expect(";");
14982ec34544SRui Ueyama }
14992ec34544SRui Ueyama 
15002ec34544SRui Ueyama // Reads a non-anonymous version definition,
15012ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
15023837f427SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef verStr) {
15032ec34544SRui Ueyama   // Read a symbol list.
15043837f427SRui Ueyama   std::vector<SymbolVersion> locals;
15053837f427SRui Ueyama   std::vector<SymbolVersion> globals;
15063837f427SRui Ueyama   std::tie(locals, globals) = readSymbols();
1507e28a70daSFangrui Song   for (const SymbolVersion &pat : locals)
1508e28a70daSFangrui Song     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
15092ec34544SRui Ueyama 
15102ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
15113837f427SRui Ueyama   VersionDefinition ver;
15123837f427SRui Ueyama   ver.name = verStr;
1513e28a70daSFangrui Song   ver.patterns = globals;
1514e28a70daSFangrui Song   ver.id = config->versionDefinitions.size();
15153837f427SRui Ueyama   config->versionDefinitions.push_back(ver);
15162ec34544SRui Ueyama 
15172ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
15182ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
15192ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
15202ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
15212ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
15225f380403SFangrui Song   if (next() != ";")
15232ec34544SRui Ueyama     expect(";");
15242ec34544SRui Ueyama }
15252ec34544SRui Ueyama 
152649279ca1SFangrui Song bool elf::hasWildcard(StringRef s) {
15273837f427SRui Ueyama   return s.find_first_of("?*[") != StringRef::npos;
15281e77ad14SRui Ueyama }
15291e77ad14SRui Ueyama 
15302ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
15312ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
15322ec34544SRui Ueyama ScriptParser::readSymbols() {
15333837f427SRui Ueyama   std::vector<SymbolVersion> locals;
15343837f427SRui Ueyama   std::vector<SymbolVersion> globals;
15353837f427SRui Ueyama   std::vector<SymbolVersion> *v = &globals;
15362ec34544SRui Ueyama 
1537b8a59c8aSBob Haarman   while (!errorCount()) {
15382ec34544SRui Ueyama     if (consume("}"))
15392ec34544SRui Ueyama       break;
15402ec34544SRui Ueyama     if (consumeLabel("local")) {
15413837f427SRui Ueyama       v = &locals;
15422ec34544SRui Ueyama       continue;
15432ec34544SRui Ueyama     }
15442ec34544SRui Ueyama     if (consumeLabel("global")) {
15453837f427SRui Ueyama       v = &globals;
15462ec34544SRui Ueyama       continue;
15472ec34544SRui Ueyama     }
15482ec34544SRui Ueyama 
15492ec34544SRui Ueyama     if (consume("extern")) {
15503837f427SRui Ueyama       std::vector<SymbolVersion> ext = readVersionExtern();
15513837f427SRui Ueyama       v->insert(v->end(), ext.begin(), ext.end());
15522ec34544SRui Ueyama     } else {
15533837f427SRui Ueyama       StringRef tok = next();
15543837f427SRui Ueyama       v->push_back({unquote(tok), false, hasWildcard(tok)});
15552ec34544SRui Ueyama     }
15562ec34544SRui Ueyama     expect(";");
15572ec34544SRui Ueyama   }
15583837f427SRui Ueyama   return {locals, globals};
15592ec34544SRui Ueyama }
15602ec34544SRui Ueyama 
15612ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
15622ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
156317324d8bSRui Ueyama //
156417324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK:
156517324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };"
15662ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
15673837f427SRui Ueyama   StringRef tok = next();
15683837f427SRui Ueyama   bool isCXX = tok == "\"C++\"";
15693837f427SRui Ueyama   if (!isCXX && tok != "\"C\"")
15702ec34544SRui Ueyama     setError("Unknown language");
15712ec34544SRui Ueyama   expect("{");
15722ec34544SRui Ueyama 
15733837f427SRui Ueyama   std::vector<SymbolVersion> ret;
1574b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
15753837f427SRui Ueyama     StringRef tok = next();
15763837f427SRui Ueyama     ret.push_back(
15773837f427SRui Ueyama         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
157817324d8bSRui Ueyama     if (consume("}"))
15793837f427SRui Ueyama       return ret;
15802ec34544SRui Ueyama     expect(";");
15812ec34544SRui Ueyama   }
15822ec34544SRui Ueyama 
15832ec34544SRui Ueyama   expect("}");
15843837f427SRui Ueyama   return ret;
15852ec34544SRui Ueyama }
15862ec34544SRui Ueyama 
158792b5b980SFangrui Song Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
15883837f427SRui Ueyama                                         StringRef s3) {
15893837f427SRui Ueyama   if (!consume(s1) && !consume(s2) && !consume(s3)) {
15903837f427SRui Ueyama     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
159192b5b980SFangrui Song     return [] { return 0; };
15922ec34544SRui Ueyama   }
15932ec34544SRui Ueyama   expect("=");
159492b5b980SFangrui Song   return readExpr();
15952ec34544SRui Ueyama }
15962ec34544SRui Ueyama 
15972ec34544SRui Ueyama // Parse the MEMORY command as specified in:
15982ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
15992ec34544SRui Ueyama //
16002ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
16012ec34544SRui Ueyama void ScriptParser::readMemory() {
16022ec34544SRui Ueyama   expect("{");
1603b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
16043837f427SRui Ueyama     StringRef tok = next();
16053837f427SRui Ueyama     if (tok == "INCLUDE") {
16062e9d40d5SRui Ueyama       readInclude();
16072e9d40d5SRui Ueyama       continue;
16082e9d40d5SRui Ueyama     }
16092ec34544SRui Ueyama 
16103837f427SRui Ueyama     uint32_t flags = 0;
16113837f427SRui Ueyama     uint32_t negFlags = 0;
16122ec34544SRui Ueyama     if (consume("(")) {
16133837f427SRui Ueyama       std::tie(flags, negFlags) = readMemoryAttributes();
16142ec34544SRui Ueyama       expect(")");
16152ec34544SRui Ueyama     }
16162ec34544SRui Ueyama     expect(":");
16172ec34544SRui Ueyama 
161892b5b980SFangrui Song     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
16192ec34544SRui Ueyama     expect(",");
162092b5b980SFangrui Song     Expr length = readMemoryAssignment("LENGTH", "len", "l");
16212ec34544SRui Ueyama 
16225f37541cSGeorge Rimar     // Add the memory region to the region map.
16233837f427SRui Ueyama     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, negFlags);
16243837f427SRui Ueyama     if (!script->memoryRegions.insert({tok, mr}).second)
16253837f427SRui Ueyama       setError("region '" + tok + "' already defined");
16262ec34544SRui Ueyama   }
16272ec34544SRui Ueyama }
16282ec34544SRui Ueyama 
16292ec34544SRui Ueyama // This function parses the attributes used to match against section
16302ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
16312ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
16322ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
16333837f427SRui Ueyama   uint32_t flags = 0;
16343837f427SRui Ueyama   uint32_t negFlags = 0;
16353837f427SRui Ueyama   bool invert = false;
16362ec34544SRui Ueyama 
16373837f427SRui Ueyama   for (char c : next().lower()) {
16383837f427SRui Ueyama     uint32_t flag = 0;
16393837f427SRui Ueyama     if (c == '!')
16403837f427SRui Ueyama       invert = !invert;
16413837f427SRui Ueyama     else if (c == 'w')
16423837f427SRui Ueyama       flag = SHF_WRITE;
16433837f427SRui Ueyama     else if (c == 'x')
16443837f427SRui Ueyama       flag = SHF_EXECINSTR;
16453837f427SRui Ueyama     else if (c == 'a')
16463837f427SRui Ueyama       flag = SHF_ALLOC;
16473837f427SRui Ueyama     else if (c != 'r')
16482ec34544SRui Ueyama       setError("invalid memory region attribute");
16492ec34544SRui Ueyama 
16503837f427SRui Ueyama     if (invert)
16513837f427SRui Ueyama       negFlags |= flag;
16522ec34544SRui Ueyama     else
16533837f427SRui Ueyama       flags |= flag;
16542ec34544SRui Ueyama   }
16553837f427SRui Ueyama   return {flags, negFlags};
16562ec34544SRui Ueyama }
16572ec34544SRui Ueyama 
165807837b8fSFangrui Song void elf::readLinkerScript(MemoryBufferRef mb) {
1659439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read linker script",
1660439341b9SJames Henderson                                  mb.getBufferIdentifier());
16613837f427SRui Ueyama   ScriptParser(mb).readLinkerScript();
16622ec34544SRui Ueyama }
16632ec34544SRui Ueyama 
166407837b8fSFangrui Song void elf::readVersionScript(MemoryBufferRef mb) {
1665439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read version script",
1666439341b9SJames Henderson                                  mb.getBufferIdentifier());
16673837f427SRui Ueyama   ScriptParser(mb).readVersionScript();
16682ec34544SRui Ueyama }
16692ec34544SRui Ueyama 
167007837b8fSFangrui Song void elf::readDynamicList(MemoryBufferRef mb) {
1671439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
167207837b8fSFangrui Song   ScriptParser(mb).readDynamicList();
16738c7e8cceSPetr Hosek }
1674bd8cfe65SFangrui Song 
167507837b8fSFangrui Song void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1676439341b9SJames Henderson   llvm::TimeTraceScope timeScope("Read defsym input", name);
167707837b8fSFangrui Song   ScriptParser(mb).readDefsym(name);
167807837b8fSFangrui Song }
1679