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(); 802ec34544SRui Ueyama void readPhdrs(); 815f37541cSGeorge Rimar void readRegionAlias(); 822ec34544SRui Ueyama void readSearchDir(); 832ec34544SRui Ueyama void readSections(); 84e262bb1aSRui Ueyama void readTarget(); 852ec34544SRui Ueyama void readVersion(); 862ec34544SRui Ueyama void readVersionScriptCommand(); 872ec34544SRui Ueyama 883837f427SRui Ueyama SymbolAssignment *readSymbolAssignment(StringRef name); 893837f427SRui Ueyama ByteCommand *readByteCommand(StringRef tok); 90b0486051SSimon Atanasyan std::array<uint8_t, 4> readFill(); 913837f427SRui Ueyama bool readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2); 923837f427SRui Ueyama void readSectionAddressType(OutputSection *cmd); 93a582419aSGeorge Rimar OutputSection *readOverlaySectionDescription(); 943837f427SRui Ueyama OutputSection *readOutputSectionDescription(StringRef outSec); 95a582419aSGeorge Rimar std::vector<BaseCommand *> readOverlay(); 962ec34544SRui Ueyama std::vector<StringRef> readOutputSectionPhdrs(); 97dbd0ad33SPeter Smith std::pair<uint64_t, uint64_t> readInputSectionFlags(); 983837f427SRui Ueyama InputSectionDescription *readInputSectionDescription(StringRef tok); 992ec34544SRui Ueyama StringMatcher readFilePatterns(); 1002ec34544SRui Ueyama std::vector<SectionPattern> readInputSectionsList(); 101dbd0ad33SPeter Smith InputSectionDescription *readInputSectionRules(StringRef filePattern, 102dbd0ad33SPeter Smith uint64_t withFlags, 103dbd0ad33SPeter Smith uint64_t withoutFlags); 1042ec34544SRui Ueyama unsigned readPhdrType(); 105*2a9aed0eSFangrui Song SortSectionPolicy peekSortKind(); 1062ec34544SRui Ueyama SortSectionPolicy readSortKind(); 1073837f427SRui Ueyama SymbolAssignment *readProvideHidden(bool provide, bool hidden); 1083837f427SRui Ueyama SymbolAssignment *readAssignment(StringRef tok); 1092ec34544SRui Ueyama void readSort(); 110d30a78b3SGeorge Rimar Expr readAssert(); 1115fb17128SGeorge Rimar Expr readConstant(); 1125fb17128SGeorge Rimar Expr getPageSize(); 1132ec34544SRui Ueyama 11492b5b980SFangrui Song Expr readMemoryAssignment(StringRef, StringRef, StringRef); 1152ec34544SRui Ueyama std::pair<uint32_t, uint32_t> readMemoryAttributes(); 1162ec34544SRui Ueyama 1173837f427SRui Ueyama Expr combine(StringRef op, Expr l, Expr r); 1182ec34544SRui Ueyama Expr readExpr(); 1193837f427SRui Ueyama Expr readExpr1(Expr lhs, int minPrec); 1202ec34544SRui Ueyama StringRef readParenLiteral(); 1212ec34544SRui Ueyama Expr readPrimary(); 1223837f427SRui Ueyama Expr readTernary(Expr cond); 1232ec34544SRui Ueyama Expr readParenExpr(); 1242ec34544SRui Ueyama 1252ec34544SRui Ueyama // For parsing version script. 1262ec34544SRui Ueyama std::vector<SymbolVersion> readVersionExtern(); 1272ec34544SRui Ueyama void readAnonymousDeclaration(); 1283837f427SRui Ueyama void readVersionDeclaration(StringRef verStr); 1292ec34544SRui Ueyama 1302ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>> 1312ec34544SRui Ueyama readSymbols(); 1322ec34544SRui Ueyama 133fd06b025SRui Ueyama // True if a script being read is in a subdirectory specified by -sysroot. 1343837f427SRui Ueyama bool isUnderSysroot = false; 1350440be4aSRui Ueyama 1360440be4aSRui Ueyama // A set to detect an INCLUDE() cycle. 1373837f427SRui Ueyama StringSet<> seen; 1382ec34544SRui Ueyama }; 13996b3fe02SRui Ueyama } // namespace 1402ec34544SRui Ueyama 1413837f427SRui Ueyama static StringRef unquote(StringRef s) { 1423837f427SRui Ueyama if (s.startswith("\"")) 1433837f427SRui Ueyama return s.substr(1, s.size() - 2); 1443837f427SRui Ueyama return s; 1451e77ad14SRui Ueyama } 1461e77ad14SRui Ueyama 1472ec34544SRui Ueyama // Some operations only support one non absolute value. Move the 1482ec34544SRui Ueyama // absolute one to the right hand side for convenience. 1493837f427SRui Ueyama static void moveAbsRight(ExprValue &a, ExprValue &b) { 1503837f427SRui Ueyama if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute())) 1513837f427SRui Ueyama std::swap(a, b); 1523837f427SRui Ueyama if (!b.isAbsolute()) 1533837f427SRui Ueyama error(a.loc + ": at least one side of the expression must be absolute"); 1542ec34544SRui Ueyama } 1552ec34544SRui Ueyama 1563837f427SRui Ueyama static ExprValue add(ExprValue a, ExprValue b) { 1573837f427SRui Ueyama moveAbsRight(a, b); 1583837f427SRui Ueyama return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc}; 1592ec34544SRui Ueyama } 1602ec34544SRui Ueyama 1613837f427SRui Ueyama static ExprValue sub(ExprValue a, ExprValue b) { 16263a4a98eSRafael Espindola // The distance between two symbols in sections is absolute. 1633837f427SRui Ueyama if (!a.isAbsolute() && !b.isAbsolute()) 1643837f427SRui Ueyama return a.getValue() - b.getValue(); 1653837f427SRui Ueyama return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc}; 1662ec34544SRui Ueyama } 1672ec34544SRui Ueyama 1683837f427SRui Ueyama static ExprValue bitAnd(ExprValue a, ExprValue b) { 1693837f427SRui Ueyama moveAbsRight(a, b); 1703837f427SRui Ueyama return {a.sec, a.forceAbsolute, 1713837f427SRui Ueyama (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc}; 1722ec34544SRui Ueyama } 1732ec34544SRui Ueyama 1743837f427SRui Ueyama static ExprValue bitOr(ExprValue a, ExprValue b) { 1753837f427SRui Ueyama moveAbsRight(a, b); 1763837f427SRui Ueyama return {a.sec, a.forceAbsolute, 1773837f427SRui Ueyama (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc}; 1782ec34544SRui Ueyama } 1792ec34544SRui Ueyama 1802ec34544SRui Ueyama void ScriptParser::readDynamicList() { 1812ec34544SRui Ueyama expect("{"); 1823837f427SRui Ueyama std::vector<SymbolVersion> locals; 1833837f427SRui Ueyama std::vector<SymbolVersion> globals; 1843837f427SRui Ueyama std::tie(locals, globals) = readSymbols(); 185d72d97b3SRafael Espindola expect(";"); 186d72d97b3SRafael Espindola 187d72d97b3SRafael Espindola if (!atEOF()) { 1882ec34544SRui Ueyama setError("EOF expected, but got " + next()); 189d72d97b3SRafael Espindola return; 190d72d97b3SRafael Espindola } 1913837f427SRui Ueyama if (!locals.empty()) { 192d72d97b3SRafael Espindola setError("\"local:\" scope not supported in --dynamic-list"); 193d72d97b3SRafael Espindola return; 194d72d97b3SRafael Espindola } 195d72d97b3SRafael Espindola 1963837f427SRui Ueyama for (SymbolVersion v : globals) 1973837f427SRui Ueyama config->dynamicList.push_back(v); 1982ec34544SRui Ueyama } 1992ec34544SRui Ueyama 2002ec34544SRui Ueyama void ScriptParser::readVersionScript() { 2012ec34544SRui Ueyama readVersionScriptCommand(); 2022ec34544SRui Ueyama if (!atEOF()) 2032ec34544SRui Ueyama setError("EOF expected, but got " + next()); 2042ec34544SRui Ueyama } 2052ec34544SRui Ueyama 2062ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() { 2072ec34544SRui Ueyama if (consume("{")) { 2082ec34544SRui Ueyama readAnonymousDeclaration(); 2092ec34544SRui Ueyama return; 2102ec34544SRui Ueyama } 2112ec34544SRui Ueyama 212b8a59c8aSBob Haarman while (!atEOF() && !errorCount() && peek() != "}") { 2133837f427SRui Ueyama StringRef verStr = next(); 2143837f427SRui Ueyama if (verStr == "{") { 2152ec34544SRui Ueyama setError("anonymous version definition is used in " 2162ec34544SRui Ueyama "combination with other version definitions"); 2172ec34544SRui Ueyama return; 2182ec34544SRui Ueyama } 2192ec34544SRui Ueyama expect("{"); 2203837f427SRui Ueyama readVersionDeclaration(verStr); 2212ec34544SRui Ueyama } 2222ec34544SRui Ueyama } 2232ec34544SRui Ueyama 2242ec34544SRui Ueyama void ScriptParser::readVersion() { 2252ec34544SRui Ueyama expect("{"); 2262ec34544SRui Ueyama readVersionScriptCommand(); 2272ec34544SRui Ueyama expect("}"); 2282ec34544SRui Ueyama } 2292ec34544SRui Ueyama 2302ec34544SRui Ueyama void ScriptParser::readLinkerScript() { 2312ec34544SRui Ueyama while (!atEOF()) { 2323837f427SRui Ueyama StringRef tok = next(); 2333837f427SRui Ueyama if (tok == ";") 2342ec34544SRui Ueyama continue; 2352ec34544SRui Ueyama 2363837f427SRui Ueyama if (tok == "ENTRY") { 2372ec34544SRui Ueyama readEntry(); 2383837f427SRui Ueyama } else if (tok == "EXTERN") { 2392ec34544SRui Ueyama readExtern(); 2403837f427SRui Ueyama } else if (tok == "GROUP") { 2412ec34544SRui Ueyama readGroup(); 2423837f427SRui Ueyama } else if (tok == "INCLUDE") { 2432ec34544SRui Ueyama readInclude(); 2443837f427SRui Ueyama } else if (tok == "INPUT") { 2451d92aa73SRui Ueyama readInput(); 2463837f427SRui Ueyama } else if (tok == "MEMORY") { 2472ec34544SRui Ueyama readMemory(); 2483837f427SRui Ueyama } else if (tok == "OUTPUT") { 2492ec34544SRui Ueyama readOutput(); 2503837f427SRui Ueyama } else if (tok == "OUTPUT_ARCH") { 2512ec34544SRui Ueyama readOutputArch(); 2523837f427SRui Ueyama } else if (tok == "OUTPUT_FORMAT") { 2532ec34544SRui Ueyama readOutputFormat(); 2543837f427SRui Ueyama } else if (tok == "PHDRS") { 2552ec34544SRui Ueyama readPhdrs(); 2563837f427SRui Ueyama } else if (tok == "REGION_ALIAS") { 2575f37541cSGeorge Rimar readRegionAlias(); 2583837f427SRui Ueyama } else if (tok == "SEARCH_DIR") { 2592ec34544SRui Ueyama readSearchDir(); 2603837f427SRui Ueyama } else if (tok == "SECTIONS") { 2612ec34544SRui Ueyama readSections(); 2623837f427SRui Ueyama } else if (tok == "TARGET") { 263e262bb1aSRui Ueyama readTarget(); 2643837f427SRui Ueyama } else if (tok == "VERSION") { 2652ec34544SRui Ueyama readVersion(); 2663837f427SRui Ueyama } else if (SymbolAssignment *cmd = readAssignment(tok)) { 2673837f427SRui Ueyama script->sectionCommands.push_back(cmd); 2682ec34544SRui Ueyama } else { 2693837f427SRui Ueyama setError("unknown directive: " + tok); 2702ec34544SRui Ueyama } 2712ec34544SRui Ueyama } 2722ec34544SRui Ueyama } 2732ec34544SRui Ueyama 2743837f427SRui Ueyama void ScriptParser::readDefsym(StringRef name) { 275c1522816SGeorge Rimar if (errorCount()) 276c1522816SGeorge Rimar return; 2773837f427SRui Ueyama Expr e = readExpr(); 2788c7e8cceSPetr Hosek if (!atEOF()) 2798c7e8cceSPetr Hosek setError("EOF expected, but got " + next()); 2803837f427SRui Ueyama SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation()); 2813837f427SRui Ueyama script->sectionCommands.push_back(cmd); 2828c7e8cceSPetr Hosek } 2838c7e8cceSPetr Hosek 2843837f427SRui Ueyama void ScriptParser::addFile(StringRef s) { 2853837f427SRui Ueyama if (isUnderSysroot && s.startswith("/")) { 2863837f427SRui Ueyama SmallString<128> pathData; 2873837f427SRui Ueyama StringRef path = (config->sysroot + s).toStringRef(pathData); 2883837f427SRui Ueyama if (sys::fs::exists(path)) { 28949a3ad21SRui Ueyama driver->addFile(saver.save(path), /*withLOption=*/false); 2902ec34544SRui Ueyama return; 2912ec34544SRui Ueyama } 2922ec34544SRui Ueyama } 2932ec34544SRui Ueyama 2943837f427SRui Ueyama if (s.startswith("/")) { 295c384ca3cSFangrui Song // Case 1: s is an absolute path. Just open it. 29649a3ad21SRui Ueyama driver->addFile(s, /*withLOption=*/false); 2973837f427SRui Ueyama } else if (s.startswith("=")) { 298c384ca3cSFangrui Song // Case 2: relative to the sysroot. 2993837f427SRui Ueyama if (config->sysroot.empty()) 30049a3ad21SRui Ueyama driver->addFile(s.substr(1), /*withLOption=*/false); 3012ec34544SRui Ueyama else 302136d27abSRui Ueyama driver->addFile(saver.save(config->sysroot + "/" + s.substr(1)), 30349a3ad21SRui Ueyama /*withLOption=*/false); 3043837f427SRui Ueyama } else if (s.startswith("-l")) { 305c384ca3cSFangrui Song // Case 3: search in the list of library paths. 3063837f427SRui Ueyama driver->addLibrary(s.substr(2)); 307c384ca3cSFangrui Song } else { 308c384ca3cSFangrui Song // Case 4: s is a relative path. Search in the directory of the script file. 309c384ca3cSFangrui Song std::string filename = std::string(getCurrentMB().getBufferIdentifier()); 310c384ca3cSFangrui Song StringRef directory = sys::path::parent_path(filename); 311c384ca3cSFangrui Song if (!directory.empty()) { 312c384ca3cSFangrui Song SmallString<0> path(directory); 313c384ca3cSFangrui Song sys::path::append(path, s); 314c384ca3cSFangrui Song if (sys::fs::exists(path)) { 315c384ca3cSFangrui Song driver->addFile(path, /*withLOption=*/false); 316c384ca3cSFangrui Song return; 317c384ca3cSFangrui Song } 318c384ca3cSFangrui Song } 319c384ca3cSFangrui Song // Then search in the current working directory. 320c384ca3cSFangrui Song if (sys::fs::exists(s)) { 32149a3ad21SRui Ueyama driver->addFile(s, /*withLOption=*/false); 3222ec34544SRui Ueyama } else { 323c384ca3cSFangrui Song // Finally, search in the list of library paths. 3243837f427SRui Ueyama if (Optional<std::string> path = findFromSearchPaths(s)) 32549a3ad21SRui Ueyama driver->addFile(saver.save(*path), /*withLOption=*/true); 3262ec34544SRui Ueyama else 3273837f427SRui Ueyama setError("unable to find " + s); 3282ec34544SRui Ueyama } 3292ec34544SRui Ueyama } 330c384ca3cSFangrui Song } 3312ec34544SRui Ueyama 3322ec34544SRui Ueyama void ScriptParser::readAsNeeded() { 3332ec34544SRui Ueyama expect("("); 3343837f427SRui Ueyama bool orig = config->asNeeded; 3353837f427SRui Ueyama config->asNeeded = true; 336b8a59c8aSBob Haarman while (!errorCount() && !consume(")")) 3372ec34544SRui Ueyama addFile(unquote(next())); 3383837f427SRui Ueyama config->asNeeded = orig; 3392ec34544SRui Ueyama } 3402ec34544SRui Ueyama 3412ec34544SRui Ueyama void ScriptParser::readEntry() { 3422ec34544SRui Ueyama // -e <symbol> takes predecence over ENTRY(<symbol>). 3432ec34544SRui Ueyama expect("("); 3443837f427SRui Ueyama StringRef tok = next(); 3453837f427SRui Ueyama if (config->entry.empty()) 3463837f427SRui Ueyama config->entry = tok; 3472ec34544SRui Ueyama expect(")"); 3482ec34544SRui Ueyama } 3492ec34544SRui Ueyama 3502ec34544SRui Ueyama void ScriptParser::readExtern() { 3512ec34544SRui Ueyama expect("("); 352b8a59c8aSBob Haarman while (!errorCount() && !consume(")")) 3533837f427SRui Ueyama config->undefined.push_back(unquote(next())); 3542ec34544SRui Ueyama } 3552ec34544SRui Ueyama 3562ec34544SRui Ueyama void ScriptParser::readGroup() { 3573837f427SRui Ueyama bool orig = InputFile::isInGroup; 3583837f427SRui Ueyama InputFile::isInGroup = true; 3591d92aa73SRui Ueyama readInput(); 3603837f427SRui Ueyama InputFile::isInGroup = orig; 3613837f427SRui Ueyama if (!orig) 3623837f427SRui Ueyama ++InputFile::nextGroupId; 3632ec34544SRui Ueyama } 3642ec34544SRui Ueyama 3652ec34544SRui Ueyama void ScriptParser::readInclude() { 3663837f427SRui Ueyama StringRef tok = unquote(next()); 3672ec34544SRui Ueyama 3683837f427SRui Ueyama if (!seen.insert(tok).second) { 3690440be4aSRui Ueyama setError("there is a cycle in linker script INCLUDEs"); 3700440be4aSRui Ueyama return; 3710440be4aSRui Ueyama } 3720440be4aSRui Ueyama 3733837f427SRui Ueyama if (Optional<std::string> path = searchScript(tok)) { 3743837f427SRui Ueyama if (Optional<MemoryBufferRef> mb = readFile(*path)) 3753837f427SRui Ueyama tokenize(*mb); 3762ec34544SRui Ueyama return; 3772ec34544SRui Ueyama } 3783837f427SRui Ueyama setError("cannot find linker script " + tok); 3792ec34544SRui Ueyama } 3802ec34544SRui Ueyama 3811d92aa73SRui Ueyama void ScriptParser::readInput() { 3821d92aa73SRui Ueyama expect("("); 3831d92aa73SRui Ueyama while (!errorCount() && !consume(")")) { 3841d92aa73SRui Ueyama if (consume("AS_NEEDED")) 3851d92aa73SRui Ueyama readAsNeeded(); 3861d92aa73SRui Ueyama else 3871d92aa73SRui Ueyama addFile(unquote(next())); 3881d92aa73SRui Ueyama } 3891d92aa73SRui Ueyama } 3901d92aa73SRui Ueyama 3912ec34544SRui Ueyama void ScriptParser::readOutput() { 3922ec34544SRui Ueyama // -o <file> takes predecence over OUTPUT(<file>). 3932ec34544SRui Ueyama expect("("); 3943837f427SRui Ueyama StringRef tok = next(); 3953837f427SRui Ueyama if (config->outputFile.empty()) 3963837f427SRui Ueyama config->outputFile = unquote(tok); 3972ec34544SRui Ueyama expect(")"); 3982ec34544SRui Ueyama } 3992ec34544SRui Ueyama 4002ec34544SRui Ueyama void ScriptParser::readOutputArch() { 4012ec34544SRui Ueyama // OUTPUT_ARCH is ignored for now. 4022ec34544SRui Ueyama expect("("); 403b8a59c8aSBob Haarman while (!errorCount() && !consume(")")) 4042ec34544SRui Ueyama skip(); 4052ec34544SRui Ueyama } 4062ec34544SRui Ueyama 4073837f427SRui Ueyama static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) { 4083837f427SRui Ueyama return StringSwitch<std::pair<ELFKind, uint16_t>>(s) 4094f8c8228SRui Ueyama .Case("elf32-i386", {ELF32LEKind, EM_386}) 4104f8c8228SRui Ueyama .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU}) 4114f8c8228SRui Ueyama .Case("elf32-littlearm", {ELF32LEKind, EM_ARM}) 4124f8c8228SRui Ueyama .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64}) 41319b134ccSDimitry Andric .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64}) 4144f8c8228SRui Ueyama .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64}) 4154134143cSRui Ueyama .Case("elf32-powerpc", {ELF32BEKind, EM_PPC}) 4164f8c8228SRui Ueyama .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64}) 4174f8c8228SRui Ueyama .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64}) 4184f8c8228SRui Ueyama .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64}) 4194134143cSRui Ueyama .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS}) 4204f8c8228SRui Ueyama .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS}) 4214f8c8228SRui Ueyama .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS}) 4224f8c8228SRui Ueyama .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS}) 4234f8c8228SRui Ueyama .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS}) 4244f8c8228SRui Ueyama .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS}) 42544d908d7SFangrui Song .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV}) 42644d908d7SFangrui Song .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV}) 427aff950e9SLemonBoy .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9}) 4284f8c8228SRui Ueyama .Default({ELFNoneKind, EM_NONE}); 429ea8cd00aSRui Ueyama } 430ea8cd00aSRui Ueyama 431ea8cd00aSRui Ueyama // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(bfdname, big, little). 432ea8cd00aSRui Ueyama // Currently we ignore big and little parameters. 4332ec34544SRui Ueyama void ScriptParser::readOutputFormat() { 4342ec34544SRui Ueyama expect("("); 435ea8cd00aSRui Ueyama 4362822852fSShoaib Meenai config->bfdname = unquote(next()); 4372822852fSShoaib Meenai StringRef s = config->bfdname; 4383837f427SRui Ueyama if (s.consume_back("-freebsd")) 4393837f427SRui Ueyama config->osabi = ELFOSABI_FREEBSD; 4404f8c8228SRui Ueyama 4413837f427SRui Ueyama std::tie(config->ekind, config->emachine) = parseBfdName(s); 4423837f427SRui Ueyama if (config->emachine == EM_NONE) 4432822852fSShoaib Meenai setError("unknown output format name: " + config->bfdname); 4443837f427SRui Ueyama if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips") 4453837f427SRui Ueyama config->mipsN32Abi = true; 446ea8cd00aSRui Ueyama 447b579c439SRui Ueyama if (consume(")")) 4482ec34544SRui Ueyama return; 449b579c439SRui Ueyama expect(","); 4502ec34544SRui Ueyama skip(); 4512ec34544SRui Ueyama expect(","); 4522ec34544SRui Ueyama skip(); 4532ec34544SRui Ueyama expect(")"); 4542ec34544SRui Ueyama } 4552ec34544SRui Ueyama 4562ec34544SRui Ueyama void ScriptParser::readPhdrs() { 4572ec34544SRui Ueyama expect("{"); 4582ec34544SRui Ueyama 459b8a59c8aSBob Haarman while (!errorCount() && !consume("}")) { 4603837f427SRui Ueyama PhdrsCommand cmd; 4613837f427SRui Ueyama cmd.name = next(); 4623837f427SRui Ueyama cmd.type = readPhdrType(); 463b579c439SRui Ueyama 464b8a59c8aSBob Haarman while (!errorCount() && !consume(";")) { 465b579c439SRui Ueyama if (consume("FILEHDR")) 4663837f427SRui Ueyama cmd.hasFilehdr = true; 467b579c439SRui Ueyama else if (consume("PHDRS")) 4683837f427SRui Ueyama cmd.hasPhdrs = true; 469b579c439SRui Ueyama else if (consume("AT")) 4703837f427SRui Ueyama cmd.lmaExpr = readParenExpr(); 471b579c439SRui Ueyama else if (consume("FLAGS")) 4723837f427SRui Ueyama cmd.flags = readParenExpr()().getValue(); 473b579c439SRui Ueyama else 474b579c439SRui Ueyama setError("unexpected header attribute: " + next()); 475b579c439SRui Ueyama } 4760ae2c24cSRui Ueyama 4773837f427SRui Ueyama script->phdrsCommands.push_back(cmd); 4782ec34544SRui Ueyama } 4792ec34544SRui Ueyama } 4802ec34544SRui Ueyama 4815f37541cSGeorge Rimar void ScriptParser::readRegionAlias() { 4825f37541cSGeorge Rimar expect("("); 4833837f427SRui Ueyama StringRef alias = unquote(next()); 4845f37541cSGeorge Rimar expect(","); 4853837f427SRui Ueyama StringRef name = next(); 4865f37541cSGeorge Rimar expect(")"); 4875f37541cSGeorge Rimar 4883837f427SRui Ueyama if (script->memoryRegions.count(alias)) 4893837f427SRui Ueyama setError("redefinition of memory region '" + alias + "'"); 4903837f427SRui Ueyama if (!script->memoryRegions.count(name)) 4913837f427SRui Ueyama setError("memory region '" + name + "' is not defined"); 4923837f427SRui Ueyama script->memoryRegions.insert({alias, script->memoryRegions[name]}); 4935f37541cSGeorge Rimar } 4945f37541cSGeorge Rimar 4952ec34544SRui Ueyama void ScriptParser::readSearchDir() { 4962ec34544SRui Ueyama expect("("); 4973837f427SRui Ueyama StringRef tok = next(); 4983837f427SRui Ueyama if (!config->nostdlib) 4993837f427SRui Ueyama config->searchPaths.push_back(unquote(tok)); 5002ec34544SRui Ueyama expect(")"); 5012ec34544SRui Ueyama } 5022ec34544SRui Ueyama 503a582419aSGeorge Rimar // This reads an overlay description. Overlays are used to describe output 504a582419aSGeorge Rimar // sections that use the same virtual memory range and normally would trigger 505a582419aSGeorge Rimar // linker's sections sanity check failures. 506a582419aSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description 507a582419aSGeorge Rimar std::vector<BaseCommand *> ScriptParser::readOverlay() { 508a582419aSGeorge Rimar // VA and LMA expressions are optional, though for simplicity of 509a582419aSGeorge Rimar // implementation we assume they are not. That is what OVERLAY was designed 510a582419aSGeorge Rimar // for first of all: to allow sections with overlapping VAs at different LMAs. 5113837f427SRui Ueyama Expr addrExpr = readExpr(); 512a582419aSGeorge Rimar expect(":"); 513a582419aSGeorge Rimar expect("AT"); 5143837f427SRui Ueyama Expr lmaExpr = readParenExpr(); 515a582419aSGeorge Rimar expect("{"); 516a582419aSGeorge Rimar 5173837f427SRui Ueyama std::vector<BaseCommand *> v; 5183837f427SRui Ueyama OutputSection *prev = nullptr; 519a582419aSGeorge Rimar while (!errorCount() && !consume("}")) { 520a582419aSGeorge Rimar // VA is the same for all sections. The LMAs are consecutive in memory 521a582419aSGeorge Rimar // starting from the base load address specified. 5223837f427SRui Ueyama OutputSection *os = readOverlaySectionDescription(); 5233837f427SRui Ueyama os->addrExpr = addrExpr; 5243837f427SRui Ueyama if (prev) 5253837f427SRui Ueyama os->lmaExpr = [=] { return prev->getLMA() + prev->size; }; 526a582419aSGeorge Rimar else 5273837f427SRui Ueyama os->lmaExpr = lmaExpr; 5283837f427SRui Ueyama v.push_back(os); 5293837f427SRui Ueyama prev = os; 530a582419aSGeorge Rimar } 531a582419aSGeorge Rimar 532a582419aSGeorge Rimar // According to the specification, at the end of the overlay, the location 533a582419aSGeorge Rimar // counter should be equal to the overlay base address plus size of the 534a582419aSGeorge Rimar // largest section seen in the overlay. 535a582419aSGeorge Rimar // Here we want to create the Dot assignment command to achieve that. 5363837f427SRui Ueyama Expr moveDot = [=] { 5373837f427SRui Ueyama uint64_t max = 0; 5383837f427SRui Ueyama for (BaseCommand *cmd : v) 5393837f427SRui Ueyama max = std::max(max, cast<OutputSection>(cmd)->size); 5403837f427SRui Ueyama return addrExpr().getValue() + max; 541a582419aSGeorge Rimar }; 5423837f427SRui Ueyama v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation())); 5433837f427SRui Ueyama return v; 544a582419aSGeorge Rimar } 545a582419aSGeorge Rimar 5462ec34544SRui Ueyama void ScriptParser::readSections() { 5472ec34544SRui Ueyama expect("{"); 5483837f427SRui Ueyama std::vector<BaseCommand *> v; 549b8a59c8aSBob Haarman while (!errorCount() && !consume("}")) { 5503837f427SRui Ueyama StringRef tok = next(); 5513837f427SRui Ueyama if (tok == "OVERLAY") { 5523837f427SRui Ueyama for (BaseCommand *cmd : readOverlay()) 5533837f427SRui Ueyama v.push_back(cmd); 554a582419aSGeorge Rimar continue; 5553837f427SRui Ueyama } else if (tok == "INCLUDE") { 5562e9d40d5SRui Ueyama readInclude(); 5572e9d40d5SRui Ueyama continue; 558a582419aSGeorge Rimar } 559a582419aSGeorge Rimar 5603837f427SRui Ueyama if (BaseCommand *cmd = readAssignment(tok)) 5613837f427SRui Ueyama v.push_back(cmd); 562d30a78b3SGeorge Rimar else 5633837f427SRui Ueyama v.push_back(readOutputSectionDescription(tok)); 5642ec34544SRui Ueyama } 5657c426fb1SFangrui Song script->sectionCommands.insert(script->sectionCommands.end(), v.begin(), 5667c426fb1SFangrui Song v.end()); 5679e2c8a9dSGeorge Rimar 5687c426fb1SFangrui Song if (atEOF() || !consume("INSERT")) { 5697c426fb1SFangrui Song script->hasSectionsCommand = true; 5709e2c8a9dSGeorge Rimar return; 5719e2c8a9dSGeorge Rimar } 5729e2c8a9dSGeorge Rimar 5737c426fb1SFangrui Song bool isAfter = false; 5747c426fb1SFangrui Song if (consume("AFTER")) 5757c426fb1SFangrui Song isAfter = true; 5767c426fb1SFangrui Song else if (!consume("BEFORE")) 5777c426fb1SFangrui Song setError("expected AFTER/BEFORE, but got '" + next() + "'"); 5787c426fb1SFangrui Song StringRef where = next(); 5797c426fb1SFangrui Song for (BaseCommand *cmd : v) 5807c426fb1SFangrui Song if (auto *os = dyn_cast<OutputSection>(cmd)) 5817c426fb1SFangrui Song script->insertCommands.push_back({os, isAfter, where}); 5822ec34544SRui Ueyama } 5832ec34544SRui Ueyama 584e262bb1aSRui Ueyama void ScriptParser::readTarget() { 585e262bb1aSRui Ueyama // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers, 586e262bb1aSRui Ueyama // we accept only a limited set of BFD names (i.e. "elf" or "binary") 587e262bb1aSRui Ueyama // for --format. We recognize only /^elf/ and "binary" in the linker 588e262bb1aSRui Ueyama // script as well. 589e262bb1aSRui Ueyama expect("("); 5903837f427SRui Ueyama StringRef tok = next(); 591e262bb1aSRui Ueyama expect(")"); 592e262bb1aSRui Ueyama 5933837f427SRui Ueyama if (tok.startswith("elf")) 5943837f427SRui Ueyama config->formatBinary = false; 5953837f427SRui Ueyama else if (tok == "binary") 5963837f427SRui Ueyama config->formatBinary = true; 597e262bb1aSRui Ueyama else 5983837f427SRui Ueyama setError("unknown target: " + tok); 599e262bb1aSRui Ueyama } 600e262bb1aSRui Ueyama 6013837f427SRui Ueyama static int precedence(StringRef op) { 6023837f427SRui Ueyama return StringSwitch<int>(op) 603a5005482SGeorge Rimar .Cases("*", "/", "%", 8) 604a5005482SGeorge Rimar .Cases("+", "-", 7) 605a5005482SGeorge Rimar .Cases("<<", ">>", 6) 606a5005482SGeorge Rimar .Cases("<", "<=", ">", ">=", "==", "!=", 5) 607a5005482SGeorge Rimar .Case("&", 4) 608a5005482SGeorge Rimar .Case("|", 3) 609a5005482SGeorge Rimar .Case("&&", 2) 610a5005482SGeorge Rimar .Case("||", 1) 6112ec34544SRui Ueyama .Default(-1); 6122ec34544SRui Ueyama } 6132ec34544SRui Ueyama 6142ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() { 615c42fe247SThomas Preud'homme StringMatcher Matcher; 616c42fe247SThomas Preud'homme 617b8a59c8aSBob Haarman while (!errorCount() && !consume(")")) 618c42fe247SThomas Preud'homme Matcher.addPattern(SingleStringMatcher(next())); 619c42fe247SThomas Preud'homme return Matcher; 6202ec34544SRui Ueyama } 6212ec34544SRui Ueyama 622*2a9aed0eSFangrui Song SortSectionPolicy ScriptParser::peekSortKind() { 623*2a9aed0eSFangrui Song return StringSwitch<SortSectionPolicy>(peek()) 624*2a9aed0eSFangrui Song .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name) 625*2a9aed0eSFangrui Song .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment) 626*2a9aed0eSFangrui Song .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority) 627*2a9aed0eSFangrui Song .Case("SORT_NONE", SortSectionPolicy::None) 628*2a9aed0eSFangrui Song .Default(SortSectionPolicy::Default); 629*2a9aed0eSFangrui Song } 630*2a9aed0eSFangrui Song 6312ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() { 632*2a9aed0eSFangrui Song SortSectionPolicy ret = peekSortKind(); 633*2a9aed0eSFangrui Song if (ret != SortSectionPolicy::Default) 634*2a9aed0eSFangrui Song skip(); 635*2a9aed0eSFangrui Song return ret; 6362ec34544SRui Ueyama } 6372ec34544SRui Ueyama 63803fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form: 63903fc8d1eSRui Ueyama // 64003fc8d1eSRui Ueyama // <contents> ::= <elem>* 64103fc8d1eSRui Ueyama // <elem> ::= <exclude>? <glob-pattern> 64203fc8d1eSRui Ueyama // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")" 64303fc8d1eSRui Ueyama // 64403fc8d1eSRui Ueyama // For example, 64503fc8d1eSRui Ueyama // 64603fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz) 64703fc8d1eSRui Ueyama // 64803fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o". 64903fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in 65003fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o. 6512ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() { 6523837f427SRui Ueyama std::vector<SectionPattern> ret; 653b8a59c8aSBob Haarman while (!errorCount() && peek() != ")") { 6543837f427SRui Ueyama StringMatcher excludeFilePat; 6552ec34544SRui Ueyama if (consume("EXCLUDE_FILE")) { 6562ec34544SRui Ueyama expect("("); 6573837f427SRui Ueyama excludeFilePat = readFilePatterns(); 6582ec34544SRui Ueyama } 6592ec34544SRui Ueyama 660c42fe247SThomas Preud'homme StringMatcher SectionMatcher; 661*2a9aed0eSFangrui Song // Break if the next token is ), EXCLUDE_FILE, or SORT*. 662*2a9aed0eSFangrui Song while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" && 663*2a9aed0eSFangrui Song peekSortKind() == SortSectionPolicy::Default) 664c42fe247SThomas Preud'homme SectionMatcher.addPattern(unquote(next())); 6652ec34544SRui Ueyama 666c42fe247SThomas Preud'homme if (!SectionMatcher.empty()) 667c42fe247SThomas Preud'homme ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)}); 668*2a9aed0eSFangrui Song else if (excludeFilePat.empty()) 669*2a9aed0eSFangrui Song break; 6702ec34544SRui Ueyama else 6712ec34544SRui Ueyama setError("section pattern is expected"); 6722ec34544SRui Ueyama } 6733837f427SRui Ueyama return ret; 6742ec34544SRui Ueyama } 6752ec34544SRui Ueyama 6762ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a 6772ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows. 6782ec34544SRui Ueyama // 6792ec34544SRui Ueyama // <patterns> ::= <section-list> 6802ec34544SRui Ueyama // | <sort> "(" <section-list> ")" 6812ec34544SRui Ueyama // | <sort> "(" <sort> "(" <section-list> ")" ")" 6822ec34544SRui Ueyama // 6832ec34544SRui Ueyama // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" 6842ec34544SRui Ueyama // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" 6852ec34544SRui Ueyama // 6862ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList(). 6872ec34544SRui Ueyama InputSectionDescription * 688dbd0ad33SPeter Smith ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags, 689dbd0ad33SPeter Smith uint64_t withoutFlags) { 690dbd0ad33SPeter Smith auto *cmd = 691dbd0ad33SPeter Smith make<InputSectionDescription>(filePattern, withFlags, withoutFlags); 6922ec34544SRui Ueyama expect("("); 6932ec34544SRui Ueyama 694b8a59c8aSBob Haarman while (!errorCount() && !consume(")")) { 6953837f427SRui Ueyama SortSectionPolicy outer = readSortKind(); 6963837f427SRui Ueyama SortSectionPolicy inner = SortSectionPolicy::Default; 6973837f427SRui Ueyama std::vector<SectionPattern> v; 6983837f427SRui Ueyama if (outer != SortSectionPolicy::Default) { 6992ec34544SRui Ueyama expect("("); 7003837f427SRui Ueyama inner = readSortKind(); 7013837f427SRui Ueyama if (inner != SortSectionPolicy::Default) { 7022ec34544SRui Ueyama expect("("); 7033837f427SRui Ueyama v = readInputSectionsList(); 7042ec34544SRui Ueyama expect(")"); 7052ec34544SRui Ueyama } else { 7063837f427SRui Ueyama v = readInputSectionsList(); 7072ec34544SRui Ueyama } 7082ec34544SRui Ueyama expect(")"); 7092ec34544SRui Ueyama } else { 7103837f427SRui Ueyama v = readInputSectionsList(); 7112ec34544SRui Ueyama } 7122ec34544SRui Ueyama 7133837f427SRui Ueyama for (SectionPattern &pat : v) { 7143837f427SRui Ueyama pat.sortInner = inner; 7153837f427SRui Ueyama pat.sortOuter = outer; 7162ec34544SRui Ueyama } 7172ec34544SRui Ueyama 7183837f427SRui Ueyama std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns)); 7192ec34544SRui Ueyama } 7203837f427SRui Ueyama return cmd; 7212ec34544SRui Ueyama } 7222ec34544SRui Ueyama 7232ec34544SRui Ueyama InputSectionDescription * 7243837f427SRui Ueyama ScriptParser::readInputSectionDescription(StringRef tok) { 7252ec34544SRui Ueyama // Input section wildcard can be surrounded by KEEP. 7262ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 727dbd0ad33SPeter Smith uint64_t withFlags = 0; 728dbd0ad33SPeter Smith uint64_t withoutFlags = 0; 7293837f427SRui Ueyama if (tok == "KEEP") { 7302ec34544SRui Ueyama expect("("); 731dbd0ad33SPeter Smith if (consume("INPUT_SECTION_FLAGS")) 732dbd0ad33SPeter Smith std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 733dbd0ad33SPeter Smith InputSectionDescription *cmd = 734dbd0ad33SPeter Smith readInputSectionRules(next(), withFlags, withoutFlags); 7352ec34544SRui Ueyama expect(")"); 7363837f427SRui Ueyama script->keptSections.push_back(cmd); 7373837f427SRui Ueyama return cmd; 7382ec34544SRui Ueyama } 739dbd0ad33SPeter Smith if (tok == "INPUT_SECTION_FLAGS") { 740dbd0ad33SPeter Smith std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 741dbd0ad33SPeter Smith tok = next(); 742dbd0ad33SPeter Smith } 743dbd0ad33SPeter Smith return readInputSectionRules(tok, withFlags, withoutFlags); 7442ec34544SRui Ueyama } 7452ec34544SRui Ueyama 7462ec34544SRui Ueyama void ScriptParser::readSort() { 7472ec34544SRui Ueyama expect("("); 7482ec34544SRui Ueyama expect("CONSTRUCTORS"); 7492ec34544SRui Ueyama expect(")"); 7502ec34544SRui Ueyama } 7512ec34544SRui Ueyama 752d30a78b3SGeorge Rimar Expr ScriptParser::readAssert() { 7532ec34544SRui Ueyama expect("("); 7543837f427SRui Ueyama Expr e = readExpr(); 7552ec34544SRui Ueyama expect(","); 7563837f427SRui Ueyama StringRef msg = unquote(next()); 7572ec34544SRui Ueyama expect(")"); 758b579c439SRui Ueyama 7592ec34544SRui Ueyama return [=] { 7603837f427SRui Ueyama if (!e().getValue()) 7612682bc3cSFangrui Song errorOrWarn(msg); 7623837f427SRui Ueyama return script->getDot(); 7632ec34544SRui Ueyama }; 7642ec34544SRui Ueyama } 7652ec34544SRui Ueyama 766a46d08ebSGeorge Rimar // Tries to read the special directive for an output section definition which 767a46d08ebSGeorge Rimar // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)". 768a46d08ebSGeorge Rimar // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below. 7693837f427SRui Ueyama bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) { 7703837f427SRui Ueyama if (tok1 != "(") 771a46d08ebSGeorge Rimar return false; 7723837f427SRui Ueyama if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" && tok2 != "OVERLAY") 773a46d08ebSGeorge Rimar return false; 774a46d08ebSGeorge Rimar 775a46d08ebSGeorge Rimar expect("("); 776a46d08ebSGeorge Rimar if (consume("NOLOAD")) { 7773837f427SRui Ueyama cmd->noload = true; 778fdc41aa2SMatt Schulte cmd->type = SHT_NOBITS; 779a46d08ebSGeorge Rimar } else { 780a46d08ebSGeorge Rimar skip(); // This is "COPY", "INFO" or "OVERLAY". 7813837f427SRui Ueyama cmd->nonAlloc = true; 782a46d08ebSGeorge Rimar } 783a46d08ebSGeorge Rimar expect(")"); 784a46d08ebSGeorge Rimar return true; 785a46d08ebSGeorge Rimar } 786a46d08ebSGeorge Rimar 7871c08e9f5SGeorge Rimar // Reads an expression and/or the special directive for an output 7881c08e9f5SGeorge Rimar // section definition. Directive is one of following: "(NOLOAD)", 7891c08e9f5SGeorge Rimar // "(COPY)", "(INFO)" or "(OVERLAY)". 7903271d370SRui Ueyama // 7913271d370SRui Ueyama // An output section name can be followed by an address expression 7921c08e9f5SGeorge Rimar // and/or directive. This grammar is not LL(1) because "(" can be 79397f4d158SGeorge Rimar // interpreted as either the beginning of some expression or beginning 7941c08e9f5SGeorge Rimar // of directive. 7953271d370SRui Ueyama // 796b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html 797fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html 7983837f427SRui Ueyama void ScriptParser::readSectionAddressType(OutputSection *cmd) { 7993837f427SRui Ueyama if (readSectionDirective(cmd, peek(), peek2())) 8003271d370SRui Ueyama return; 8013271d370SRui Ueyama 8023837f427SRui Ueyama cmd->addrExpr = readExpr(); 8033837f427SRui Ueyama if (peek() == "(" && !readSectionDirective(cmd, "(", peek2())) 804a46d08ebSGeorge Rimar setError("unknown section directive: " + peek2()); 805fbb0463fSGeorge Rimar } 806fbb0463fSGeorge Rimar 8073837f427SRui Ueyama static Expr checkAlignment(Expr e, std::string &loc) { 808f22ec9ddSGeorge Rimar return [=] { 8093837f427SRui Ueyama uint64_t alignment = std::max((uint64_t)1, e().getValue()); 8103837f427SRui Ueyama if (!isPowerOf2_64(alignment)) { 8113837f427SRui Ueyama error(loc + ": alignment must be power of 2"); 812f22ec9ddSGeorge Rimar return (uint64_t)1; // Return a dummy value. 813f22ec9ddSGeorge Rimar } 8143837f427SRui Ueyama return alignment; 815f22ec9ddSGeorge Rimar }; 816f22ec9ddSGeorge Rimar } 817f22ec9ddSGeorge Rimar 818a582419aSGeorge Rimar OutputSection *ScriptParser::readOverlaySectionDescription() { 8193837f427SRui Ueyama OutputSection *cmd = 8203837f427SRui Ueyama script->createOutputSection(next(), getCurrentLocation()); 8213837f427SRui Ueyama cmd->inOverlay = true; 822a582419aSGeorge Rimar expect("{"); 823dbd0ad33SPeter Smith while (!errorCount() && !consume("}")) { 824dbd0ad33SPeter Smith uint64_t withFlags = 0; 825dbd0ad33SPeter Smith uint64_t withoutFlags = 0; 826dbd0ad33SPeter Smith if (consume("INPUT_SECTION_FLAGS")) 827dbd0ad33SPeter Smith std::tie(withFlags, withoutFlags) = readInputSectionFlags(); 828dbd0ad33SPeter Smith cmd->sectionCommands.push_back( 829dbd0ad33SPeter Smith readInputSectionRules(next(), withFlags, withoutFlags)); 830dbd0ad33SPeter Smith } 8313837f427SRui Ueyama return cmd; 832a582419aSGeorge Rimar } 833a582419aSGeorge Rimar 8343837f427SRui Ueyama OutputSection *ScriptParser::readOutputSectionDescription(StringRef outSec) { 8353837f427SRui Ueyama OutputSection *cmd = 8363837f427SRui Ueyama script->createOutputSection(outSec, getCurrentLocation()); 8373271d370SRui Ueyama 8383837f427SRui Ueyama size_t symbolsReferenced = script->referencedSymbols.size(); 839c4df670dSGeorge Rimar 8403271d370SRui Ueyama if (peek() != ":") 8413837f427SRui Ueyama readSectionAddressType(cmd); 8422ec34544SRui Ueyama expect(":"); 8432ec34544SRui Ueyama 8443837f427SRui Ueyama std::string location = getCurrentLocation(); 8452ec34544SRui Ueyama if (consume("AT")) 8463837f427SRui Ueyama cmd->lmaExpr = readParenExpr(); 8472ec34544SRui Ueyama if (consume("ALIGN")) 8483837f427SRui Ueyama cmd->alignExpr = checkAlignment(readParenExpr(), location); 8492ec34544SRui Ueyama if (consume("SUBALIGN")) 8503837f427SRui Ueyama cmd->subalignExpr = checkAlignment(readParenExpr(), location); 8512ec34544SRui Ueyama 8522ec34544SRui Ueyama // Parse constraints. 8532ec34544SRui Ueyama if (consume("ONLY_IF_RO")) 8543837f427SRui Ueyama cmd->constraint = ConstraintKind::ReadOnly; 8552ec34544SRui Ueyama if (consume("ONLY_IF_RW")) 8563837f427SRui Ueyama cmd->constraint = ConstraintKind::ReadWrite; 8572ec34544SRui Ueyama expect("{"); 8582ec34544SRui Ueyama 859b8a59c8aSBob Haarman while (!errorCount() && !consume("}")) { 8603837f427SRui Ueyama StringRef tok = next(); 8613837f427SRui Ueyama if (tok == ";") { 8622ec34544SRui Ueyama // Empty commands are allowed. Do nothing here. 8633837f427SRui Ueyama } else if (SymbolAssignment *assign = readAssignment(tok)) { 8643837f427SRui Ueyama cmd->sectionCommands.push_back(assign); 8653837f427SRui Ueyama } else if (ByteCommand *data = readByteCommand(tok)) { 8663837f427SRui Ueyama cmd->sectionCommands.push_back(data); 8673837f427SRui Ueyama } else if (tok == "CONSTRUCTORS") { 8682ec34544SRui Ueyama // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors 8692ec34544SRui Ueyama // by name. This is for very old file formats such as ECOFF/XCOFF. 8702ec34544SRui Ueyama // For ELF, we should ignore. 8713837f427SRui Ueyama } else if (tok == "FILL") { 8720810f16fSGeorge Rimar // We handle the FILL command as an alias for =fillexp section attribute, 8730810f16fSGeorge Rimar // which is different from what GNU linkers do. 8740810f16fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html 875bb7d2b17SGeorgii Rymar if (peek() != "(") 876bb7d2b17SGeorgii Rymar setError("( expected, but got " + peek()); 8773837f427SRui Ueyama cmd->filler = readFill(); 8783837f427SRui Ueyama } else if (tok == "SORT") { 8792ec34544SRui Ueyama readSort(); 8803837f427SRui Ueyama } else if (tok == "INCLUDE") { 8812e9d40d5SRui Ueyama readInclude(); 8822ec34544SRui Ueyama } else if (peek() == "(") { 8833837f427SRui Ueyama cmd->sectionCommands.push_back(readInputSectionDescription(tok)); 8842ec34544SRui Ueyama } else { 885f49fe218SGeorge Rimar // We have a file name and no input sections description. It is not a 886f49fe218SGeorge Rimar // commonly used syntax, but still acceptable. In that case, all sections 887f49fe218SGeorge Rimar // from the file will be included. 888dbd0ad33SPeter Smith // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not 889dbd0ad33SPeter Smith // handle this case here as it will already have been matched by the 890dbd0ad33SPeter Smith // case above. 8913837f427SRui Ueyama auto *isd = make<InputSectionDescription>(tok); 892c42fe247SThomas Preud'homme isd->sectionPatterns.push_back({{}, StringMatcher("*")}); 8933837f427SRui Ueyama cmd->sectionCommands.push_back(isd); 8942ec34544SRui Ueyama } 8952ec34544SRui Ueyama } 8962ec34544SRui Ueyama 8972ec34544SRui Ueyama if (consume(">")) 898adcd0268SBenjamin Kramer cmd->memoryRegionName = std::string(next()); 8992ec34544SRui Ueyama 9005d01a8beSGeorge Rimar if (consume("AT")) { 9015d01a8beSGeorge Rimar expect(">"); 902adcd0268SBenjamin Kramer cmd->lmaRegionName = std::string(next()); 9035d01a8beSGeorge Rimar } 9045d01a8beSGeorge Rimar 9053837f427SRui Ueyama if (cmd->lmaExpr && !cmd->lmaRegionName.empty()) 9065d01a8beSGeorge Rimar error("section can't have both LMA and a load region"); 9075d01a8beSGeorge Rimar 9083837f427SRui Ueyama cmd->phdrs = readOutputSectionPhdrs(); 9092ec34544SRui Ueyama 9100810f16fSGeorge Rimar if (peek() == "=" || peek().startswith("=")) { 9113837f427SRui Ueyama inExpr = true; 9120810f16fSGeorge Rimar consume("="); 9133837f427SRui Ueyama cmd->filler = readFill(); 9143837f427SRui Ueyama inExpr = false; 9150810f16fSGeorge Rimar } 9162ec34544SRui Ueyama 9172ec34544SRui Ueyama // Consume optional comma following output section command. 9182ec34544SRui Ueyama consume(","); 9192ec34544SRui Ueyama 9203837f427SRui Ueyama if (script->referencedSymbols.size() > symbolsReferenced) 9213837f427SRui Ueyama cmd->expressionsUseSymbols = true; 9223837f427SRui Ueyama return cmd; 9232ec34544SRui Ueyama } 9242ec34544SRui Ueyama 9250810f16fSGeorge Rimar // Reads a `=<fillexp>` expression and returns its value as a big-endian number. 9262ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html 9270810f16fSGeorge Rimar // We do not support using symbols in such expressions. 9282ec34544SRui Ueyama // 9298acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary 9308acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number. 9318acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement. 932bb7d2b17SGeorgii Rymar // Also, we require that expressions with operators must be wrapped into 933bb7d2b17SGeorgii Rymar // round brackets. We did it to resolve the ambiguity when parsing scripts like: 934bb7d2b17SGeorgii Rymar // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } } 9350810f16fSGeorge Rimar std::array<uint8_t, 4> ScriptParser::readFill() { 936bb7d2b17SGeorgii Rymar uint64_t value = readPrimary()().val; 9373837f427SRui Ueyama if (value > UINT32_MAX) 9380810f16fSGeorge Rimar setError("filler expression result does not fit 32-bit: 0x" + 9393837f427SRui Ueyama Twine::utohexstr(value)); 940b58079d4SRui Ueyama 9413837f427SRui Ueyama std::array<uint8_t, 4> buf; 9423837f427SRui Ueyama write32be(buf.data(), (uint32_t)value); 9433837f427SRui Ueyama return buf; 9442ec34544SRui Ueyama } 9452ec34544SRui Ueyama 9463837f427SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) { 9472ec34544SRui Ueyama expect("("); 9483837f427SRui Ueyama SymbolAssignment *cmd = readSymbolAssignment(next()); 9493837f427SRui Ueyama cmd->provide = provide; 9503837f427SRui Ueyama cmd->hidden = hidden; 9512ec34544SRui Ueyama expect(")"); 9523837f427SRui Ueyama return cmd; 9532ec34544SRui Ueyama } 9542ec34544SRui Ueyama 9553837f427SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef tok) { 956d30a78b3SGeorge Rimar // Assert expression returns Dot, so this is equal to ".=." 9573837f427SRui Ueyama if (tok == "ASSERT") 958d30a78b3SGeorge Rimar return make<SymbolAssignment>(".", readAssert(), getCurrentLocation()); 959d30a78b3SGeorge Rimar 9603837f427SRui Ueyama size_t oldPos = pos; 9613837f427SRui Ueyama SymbolAssignment *cmd = nullptr; 962e88b76a9SGeorge Rimar if (peek() == "=" || peek() == "+=") 9633837f427SRui Ueyama cmd = readSymbolAssignment(tok); 9643837f427SRui Ueyama else if (tok == "PROVIDE") 9653837f427SRui Ueyama cmd = readProvideHidden(true, false); 9663837f427SRui Ueyama else if (tok == "HIDDEN") 9673837f427SRui Ueyama cmd = readProvideHidden(false, true); 9683837f427SRui Ueyama else if (tok == "PROVIDE_HIDDEN") 9693837f427SRui Ueyama cmd = readProvideHidden(true, true); 970e88b76a9SGeorge Rimar 9713837f427SRui Ueyama if (cmd) { 9723837f427SRui Ueyama cmd->commandString = 9733837f427SRui Ueyama tok.str() + " " + 9743837f427SRui Ueyama llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " "); 975e88b76a9SGeorge Rimar expect(";"); 9762ec34544SRui Ueyama } 9773837f427SRui Ueyama return cmd; 9782ec34544SRui Ueyama } 9792ec34544SRui Ueyama 9803837f427SRui Ueyama SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) { 9813837f427SRui Ueyama StringRef op = next(); 9823837f427SRui Ueyama assert(op == "=" || op == "+="); 9833837f427SRui Ueyama Expr e = readExpr(); 9843837f427SRui Ueyama if (op == "+=") { 9853837f427SRui Ueyama std::string loc = getCurrentLocation(); 9863837f427SRui Ueyama e = [=] { return add(script->getSymbolValue(name, loc), e()); }; 9872ec34544SRui Ueyama } 9883837f427SRui Ueyama return make<SymbolAssignment>(name, e, getCurrentLocation()); 9892ec34544SRui Ueyama } 9902ec34544SRui Ueyama 9912ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker 9922ec34544SRui Ueyama // script expression. 9932ec34544SRui Ueyama Expr ScriptParser::readExpr() { 9942ec34544SRui Ueyama // Our lexer is context-aware. Set the in-expression bit so that 9952ec34544SRui Ueyama // they apply different tokenization rules. 9963837f427SRui Ueyama bool orig = inExpr; 9973837f427SRui Ueyama inExpr = true; 9983837f427SRui Ueyama Expr e = readExpr1(readPrimary(), 0); 9993837f427SRui Ueyama inExpr = orig; 10003837f427SRui Ueyama return e; 10012ec34544SRui Ueyama } 10022ec34544SRui Ueyama 10033837f427SRui Ueyama Expr ScriptParser::combine(StringRef op, Expr l, Expr r) { 10043837f427SRui Ueyama if (op == "+") 10053837f427SRui Ueyama return [=] { return add(l(), r()); }; 10063837f427SRui Ueyama if (op == "-") 10073837f427SRui Ueyama return [=] { return sub(l(), r()); }; 10083837f427SRui Ueyama if (op == "*") 10093837f427SRui Ueyama return [=] { return l().getValue() * r().getValue(); }; 10103837f427SRui Ueyama if (op == "/") { 10113837f427SRui Ueyama std::string loc = getCurrentLocation(); 10127b91e213SGeorge Rimar return [=]() -> uint64_t { 10133837f427SRui Ueyama if (uint64_t rv = r().getValue()) 10143837f427SRui Ueyama return l().getValue() / rv; 10153837f427SRui Ueyama error(loc + ": division by zero"); 1016067617f9SRui Ueyama return 0; 10177b91e213SGeorge Rimar }; 10187b91e213SGeorge Rimar } 10193837f427SRui Ueyama if (op == "%") { 10203837f427SRui Ueyama std::string loc = getCurrentLocation(); 10217b91e213SGeorge Rimar return [=]() -> uint64_t { 10223837f427SRui Ueyama if (uint64_t rv = r().getValue()) 10233837f427SRui Ueyama return l().getValue() % rv; 10243837f427SRui Ueyama error(loc + ": modulo by zero"); 1025067617f9SRui Ueyama return 0; 10267b91e213SGeorge Rimar }; 10277b91e213SGeorge Rimar } 10283837f427SRui Ueyama if (op == "<<") 10293837f427SRui Ueyama return [=] { return l().getValue() << r().getValue(); }; 10303837f427SRui Ueyama if (op == ">>") 10313837f427SRui Ueyama return [=] { return l().getValue() >> r().getValue(); }; 10323837f427SRui Ueyama if (op == "<") 10333837f427SRui Ueyama return [=] { return l().getValue() < r().getValue(); }; 10343837f427SRui Ueyama if (op == ">") 10353837f427SRui Ueyama return [=] { return l().getValue() > r().getValue(); }; 10363837f427SRui Ueyama if (op == ">=") 10373837f427SRui Ueyama return [=] { return l().getValue() >= r().getValue(); }; 10383837f427SRui Ueyama if (op == "<=") 10393837f427SRui Ueyama return [=] { return l().getValue() <= r().getValue(); }; 10403837f427SRui Ueyama if (op == "==") 10413837f427SRui Ueyama return [=] { return l().getValue() == r().getValue(); }; 10423837f427SRui Ueyama if (op == "!=") 10433837f427SRui Ueyama return [=] { return l().getValue() != r().getValue(); }; 10443837f427SRui Ueyama if (op == "||") 10453837f427SRui Ueyama return [=] { return l().getValue() || r().getValue(); }; 10463837f427SRui Ueyama if (op == "&&") 10473837f427SRui Ueyama return [=] { return l().getValue() && r().getValue(); }; 10483837f427SRui Ueyama if (op == "&") 10493837f427SRui Ueyama return [=] { return bitAnd(l(), r()); }; 10503837f427SRui Ueyama if (op == "|") 10513837f427SRui Ueyama return [=] { return bitOr(l(), r()); }; 10522ec34544SRui Ueyama llvm_unreachable("invalid operator"); 10532ec34544SRui Ueyama } 10542ec34544SRui Ueyama 10552ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function 10562ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator. 10573837f427SRui Ueyama Expr ScriptParser::readExpr1(Expr lhs, int minPrec) { 1058b8a59c8aSBob Haarman while (!atEOF() && !errorCount()) { 10592ec34544SRui Ueyama // Read an operator and an expression. 10602ec34544SRui Ueyama if (consume("?")) 10613837f427SRui Ueyama return readTernary(lhs); 10623837f427SRui Ueyama StringRef op1 = peek(); 10633837f427SRui Ueyama if (precedence(op1) < minPrec) 10642ec34544SRui Ueyama break; 10652ec34544SRui Ueyama skip(); 10663837f427SRui Ueyama Expr rhs = readPrimary(); 10672ec34544SRui Ueyama 10682ec34544SRui Ueyama // Evaluate the remaining part of the expression first if the 10692ec34544SRui Ueyama // next operator has greater precedence than the previous one. 10702ec34544SRui Ueyama // For example, if we have read "+" and "3", and if the next 10712ec34544SRui Ueyama // operator is "*", then we'll evaluate 3 * ... part first. 10722ec34544SRui Ueyama while (!atEOF()) { 10733837f427SRui Ueyama StringRef op2 = peek(); 10743837f427SRui Ueyama if (precedence(op2) <= precedence(op1)) 10752ec34544SRui Ueyama break; 10763837f427SRui Ueyama rhs = readExpr1(rhs, precedence(op2)); 10772ec34544SRui Ueyama } 10782ec34544SRui Ueyama 10793837f427SRui Ueyama lhs = combine(op1, lhs, rhs); 10802ec34544SRui Ueyama } 10813837f427SRui Ueyama return lhs; 10822ec34544SRui Ueyama } 10832ec34544SRui Ueyama 10845fb17128SGeorge Rimar Expr ScriptParser::getPageSize() { 10853837f427SRui Ueyama std::string location = getCurrentLocation(); 10865fb17128SGeorge Rimar return [=]() -> uint64_t { 10873837f427SRui Ueyama if (target) 10883837f427SRui Ueyama return config->commonPageSize; 10893837f427SRui Ueyama error(location + ": unable to calculate page size"); 10905fb17128SGeorge Rimar return 4096; // Return a dummy value. 10915fb17128SGeorge Rimar }; 10925fb17128SGeorge Rimar } 10935fb17128SGeorge Rimar 10945fb17128SGeorge Rimar Expr ScriptParser::readConstant() { 10953837f427SRui Ueyama StringRef s = readParenLiteral(); 10963837f427SRui Ueyama if (s == "COMMONPAGESIZE") 10975fb17128SGeorge Rimar return getPageSize(); 10983837f427SRui Ueyama if (s == "MAXPAGESIZE") 10993837f427SRui Ueyama return [] { return config->maxPageSize; }; 11003837f427SRui Ueyama setError("unknown constant: " + s); 1101b068b037SGeorge Rimar return [] { return 0; }; 11022ec34544SRui Ueyama } 11032ec34544SRui Ueyama 11045c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with 11055c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may 11065c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes. 11073837f427SRui Ueyama static Optional<uint64_t> parseInt(StringRef tok) { 11082ec34544SRui Ueyama // Hexadecimal 11093837f427SRui Ueyama uint64_t val; 11103837f427SRui Ueyama if (tok.startswith_lower("0x")) { 11113837f427SRui Ueyama if (!to_integer(tok.substr(2), val, 16)) 11124092016bSRui Ueyama return None; 11133837f427SRui Ueyama return val; 11144092016bSRui Ueyama } 11153837f427SRui Ueyama if (tok.endswith_lower("H")) { 11163837f427SRui Ueyama if (!to_integer(tok.drop_back(), val, 16)) 11174092016bSRui Ueyama return None; 11183837f427SRui Ueyama return val; 11194092016bSRui Ueyama } 11202ec34544SRui Ueyama 11212ec34544SRui Ueyama // Decimal 11223837f427SRui Ueyama if (tok.endswith_lower("K")) { 11233837f427SRui Ueyama if (!to_integer(tok.drop_back(), val, 10)) 11245c65088fSRui Ueyama return None; 11253837f427SRui Ueyama return val * 1024; 11262ec34544SRui Ueyama } 11273837f427SRui Ueyama if (tok.endswith_lower("M")) { 11283837f427SRui Ueyama if (!to_integer(tok.drop_back(), val, 10)) 11295c65088fSRui Ueyama return None; 11303837f427SRui Ueyama return val * 1024 * 1024; 11315c65088fSRui Ueyama } 11323837f427SRui Ueyama if (!to_integer(tok, val, 10)) 11335c65088fSRui Ueyama return None; 11343837f427SRui Ueyama return val; 11352ec34544SRui Ueyama } 11362ec34544SRui Ueyama 11373837f427SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef tok) { 11383837f427SRui Ueyama int size = StringSwitch<int>(tok) 11392ec34544SRui Ueyama .Case("BYTE", 1) 11402ec34544SRui Ueyama .Case("SHORT", 2) 11412ec34544SRui Ueyama .Case("LONG", 4) 11422ec34544SRui Ueyama .Case("QUAD", 8) 11432ec34544SRui Ueyama .Default(-1); 11443837f427SRui Ueyama if (size == -1) 11452ec34544SRui Ueyama return nullptr; 114684bcabcbSGeorge Rimar 11473837f427SRui Ueyama size_t oldPos = pos; 11483837f427SRui Ueyama Expr e = readParenExpr(); 11493837f427SRui Ueyama std::string commandString = 11503837f427SRui Ueyama tok.str() + " " + 11513837f427SRui Ueyama llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " "); 11523837f427SRui Ueyama return make<ByteCommand>(e, size, commandString); 11532ec34544SRui Ueyama } 11542ec34544SRui Ueyama 1155dbd0ad33SPeter Smith static llvm::Optional<uint64_t> parseFlag(StringRef tok) { 1156dbd0ad33SPeter Smith if (llvm::Optional<uint64_t> asInt = parseInt(tok)) 1157dbd0ad33SPeter Smith return asInt; 1158dbd0ad33SPeter Smith #define CASE_ENT(enum) #enum, ELF::enum 1159dbd0ad33SPeter Smith return StringSwitch<llvm::Optional<uint64_t>>(tok) 1160dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_WRITE)) 1161dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_ALLOC)) 1162dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_EXECINSTR)) 1163dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_MERGE)) 1164dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_STRINGS)) 1165dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_INFO_LINK)) 1166dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_LINK_ORDER)) 1167dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_OS_NONCONFORMING)) 1168dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_GROUP)) 1169dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_TLS)) 1170dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_COMPRESSED)) 1171dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_EXCLUDE)) 1172dbd0ad33SPeter Smith .Case(CASE_ENT(SHF_ARM_PURECODE)) 1173dbd0ad33SPeter Smith .Default(None); 1174dbd0ad33SPeter Smith #undef CASE_ENT 1175dbd0ad33SPeter Smith } 1176dbd0ad33SPeter Smith 1177dbd0ad33SPeter Smith // Reads the '(' <flags> ')' list of section flags in 1178dbd0ad33SPeter Smith // INPUT_SECTION_FLAGS '(' <flags> ')' in the 1179dbd0ad33SPeter Smith // following form: 1180dbd0ad33SPeter Smith // <flags> ::= <flag> 1181dbd0ad33SPeter Smith // | <flags> & flag 1182dbd0ad33SPeter Smith // <flag> ::= Recognized Flag Name, or Integer value of flag. 1183dbd0ad33SPeter Smith // If the first character of <flag> is a ! then this means without flag, 1184dbd0ad33SPeter Smith // otherwise with flag. 1185dbd0ad33SPeter Smith // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and 1186dbd0ad33SPeter Smith // without flag SHF_WRITE. 1187dbd0ad33SPeter Smith std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() { 1188dbd0ad33SPeter Smith uint64_t withFlags = 0; 1189dbd0ad33SPeter Smith uint64_t withoutFlags = 0; 1190dbd0ad33SPeter Smith expect("("); 1191dbd0ad33SPeter Smith while (!errorCount()) { 1192dbd0ad33SPeter Smith StringRef tok = unquote(next()); 1193dbd0ad33SPeter Smith bool without = tok.consume_front("!"); 1194dbd0ad33SPeter Smith if (llvm::Optional<uint64_t> flag = parseFlag(tok)) { 1195dbd0ad33SPeter Smith if (without) 1196dbd0ad33SPeter Smith withoutFlags |= *flag; 1197dbd0ad33SPeter Smith else 1198dbd0ad33SPeter Smith withFlags |= *flag; 1199dbd0ad33SPeter Smith } else { 1200dbd0ad33SPeter Smith setError("unrecognised flag: " + tok); 1201dbd0ad33SPeter Smith } 1202dbd0ad33SPeter Smith if (consume(")")) 1203dbd0ad33SPeter Smith break; 1204dbd0ad33SPeter Smith if (!consume("&")) { 1205dbd0ad33SPeter Smith next(); 1206dbd0ad33SPeter Smith setError("expected & or )"); 1207dbd0ad33SPeter Smith } 1208dbd0ad33SPeter Smith } 1209dbd0ad33SPeter Smith return std::make_pair(withFlags, withoutFlags); 1210dbd0ad33SPeter Smith } 1211dbd0ad33SPeter Smith 12122ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() { 12132ec34544SRui Ueyama expect("("); 12143837f427SRui Ueyama bool orig = inExpr; 12153837f427SRui Ueyama inExpr = false; 12163837f427SRui Ueyama StringRef tok = next(); 12173837f427SRui Ueyama inExpr = orig; 12182ec34544SRui Ueyama expect(")"); 12193837f427SRui Ueyama return tok; 12202ec34544SRui Ueyama } 12212ec34544SRui Ueyama 12223837f427SRui Ueyama static void checkIfExists(OutputSection *cmd, StringRef location) { 12233837f427SRui Ueyama if (cmd->location.empty() && script->errorOnMissingSection) 12243837f427SRui Ueyama error(location + ": undefined section " + cmd->name); 122505c4f67cSRafael Espindola } 122605c4f67cSRafael Espindola 12272ec34544SRui Ueyama Expr ScriptParser::readPrimary() { 12282ec34544SRui Ueyama if (peek() == "(") 12292ec34544SRui Ueyama return readParenExpr(); 12302ec34544SRui Ueyama 12315c65088fSRui Ueyama if (consume("~")) { 12323837f427SRui Ueyama Expr e = readPrimary(); 12333837f427SRui Ueyama return [=] { return ~e().getValue(); }; 12342ec34544SRui Ueyama } 12356f1d954eSHafiz Abid Qadeer if (consume("!")) { 12363837f427SRui Ueyama Expr e = readPrimary(); 12373837f427SRui Ueyama return [=] { return !e().getValue(); }; 12386f1d954eSHafiz Abid Qadeer } 12395c65088fSRui Ueyama if (consume("-")) { 12403837f427SRui Ueyama Expr e = readPrimary(); 12413837f427SRui Ueyama return [=] { return -e().getValue(); }; 12422ec34544SRui Ueyama } 12432ec34544SRui Ueyama 12443837f427SRui Ueyama StringRef tok = next(); 12453837f427SRui Ueyama std::string location = getCurrentLocation(); 12465c65088fSRui Ueyama 12472ec34544SRui Ueyama // Built-in functions are parsed here. 12482ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 12493837f427SRui Ueyama if (tok == "ABSOLUTE") { 12503837f427SRui Ueyama Expr inner = readParenExpr(); 12512ec34544SRui Ueyama return [=] { 12523837f427SRui Ueyama ExprValue i = inner(); 12533837f427SRui Ueyama i.forceAbsolute = true; 12543837f427SRui Ueyama return i; 12552ec34544SRui Ueyama }; 12562ec34544SRui Ueyama } 12573837f427SRui Ueyama if (tok == "ADDR") { 12583837f427SRui Ueyama StringRef name = readParenLiteral(); 12593837f427SRui Ueyama OutputSection *sec = script->getOrCreateOutputSection(name); 12603837f427SRui Ueyama sec->usedInExpression = true; 126141c7ab4aSGeorge Rimar return [=]() -> ExprValue { 12623837f427SRui Ueyama checkIfExists(sec, location); 12633837f427SRui Ueyama return {sec, false, 0, location}; 126441c7ab4aSGeorge Rimar }; 12652ec34544SRui Ueyama } 12663837f427SRui Ueyama if (tok == "ALIGN") { 12672ec34544SRui Ueyama expect("("); 12683837f427SRui Ueyama Expr e = readExpr(); 1269f22ec9ddSGeorge Rimar if (consume(")")) { 12703837f427SRui Ueyama e = checkAlignment(e, location); 12713837f427SRui Ueyama return [=] { return alignTo(script->getDot(), e().getValue()); }; 1272f22ec9ddSGeorge Rimar } 1273b579c439SRui Ueyama expect(","); 12743837f427SRui Ueyama Expr e2 = checkAlignment(readExpr(), location); 12752ec34544SRui Ueyama expect(")"); 12763c6de1a6SPetr Hosek return [=] { 12773837f427SRui Ueyama ExprValue v = e(); 12783837f427SRui Ueyama v.alignment = e2().getValue(); 12793837f427SRui Ueyama return v; 12803c6de1a6SPetr Hosek }; 12812ec34544SRui Ueyama } 12823837f427SRui Ueyama if (tok == "ALIGNOF") { 12833837f427SRui Ueyama StringRef name = readParenLiteral(); 12843837f427SRui Ueyama OutputSection *cmd = script->getOrCreateOutputSection(name); 1285617e2f98SRui Ueyama return [=] { 12863837f427SRui Ueyama checkIfExists(cmd, location); 12873837f427SRui Ueyama return cmd->alignment; 1288617e2f98SRui Ueyama }; 12892ec34544SRui Ueyama } 12903837f427SRui Ueyama if (tok == "ASSERT") 1291d30a78b3SGeorge Rimar return readAssert(); 12923837f427SRui Ueyama if (tok == "CONSTANT") 12935fb17128SGeorge Rimar return readConstant(); 12943837f427SRui Ueyama if (tok == "DATA_SEGMENT_ALIGN") { 12952ec34544SRui Ueyama expect("("); 12963837f427SRui Ueyama Expr e = readExpr(); 12972ec34544SRui Ueyama expect(","); 12982ec34544SRui Ueyama readExpr(); 12992ec34544SRui Ueyama expect(")"); 130060833f6eSGeorge Rimar return [=] { 13013837f427SRui Ueyama return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue())); 130260833f6eSGeorge Rimar }; 13032ec34544SRui Ueyama } 13043837f427SRui Ueyama if (tok == "DATA_SEGMENT_END") { 13052ec34544SRui Ueyama expect("("); 13062ec34544SRui Ueyama expect("."); 13072ec34544SRui Ueyama expect(")"); 13083837f427SRui Ueyama return [] { return script->getDot(); }; 13092ec34544SRui Ueyama } 13103837f427SRui Ueyama if (tok == "DATA_SEGMENT_RELRO_END") { 13112ec34544SRui Ueyama // GNU linkers implements more complicated logic to handle 13122ec34544SRui Ueyama // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and 13132ec34544SRui Ueyama // just align to the next page boundary for simplicity. 13142ec34544SRui Ueyama expect("("); 13152ec34544SRui Ueyama readExpr(); 13162ec34544SRui Ueyama expect(","); 13172ec34544SRui Ueyama readExpr(); 13182ec34544SRui Ueyama expect(")"); 13193837f427SRui Ueyama Expr e = getPageSize(); 13203837f427SRui Ueyama return [=] { return alignTo(script->getDot(), e().getValue()); }; 13212ec34544SRui Ueyama } 13223837f427SRui Ueyama if (tok == "DEFINED") { 13233837f427SRui Ueyama StringRef name = readParenLiteral(); 13241f166edeSHafiz Abid Qadeer return [=] { 13251f166edeSHafiz Abid Qadeer Symbol *b = symtab->find(name); 13261f166edeSHafiz Abid Qadeer return (b && b->isDefined()) ? 1 : 0; 13271f166edeSHafiz Abid Qadeer }; 13282ec34544SRui Ueyama } 13293837f427SRui Ueyama if (tok == "LENGTH") { 13303837f427SRui Ueyama StringRef name = readParenLiteral(); 13313837f427SRui Ueyama if (script->memoryRegions.count(name) == 0) { 13323837f427SRui Ueyama setError("memory region not defined: " + name); 1333b068b037SGeorge Rimar return [] { return 0; }; 1334b068b037SGeorge Rimar } 133592b5b980SFangrui Song return script->memoryRegions[name]->length; 133691b95b61SRui Ueyama } 13373837f427SRui Ueyama if (tok == "LOADADDR") { 13383837f427SRui Ueyama StringRef name = readParenLiteral(); 13393837f427SRui Ueyama OutputSection *cmd = script->getOrCreateOutputSection(name); 13403837f427SRui Ueyama cmd->usedInExpression = true; 1341617e2f98SRui Ueyama return [=] { 13423837f427SRui Ueyama checkIfExists(cmd, location); 13433837f427SRui Ueyama return cmd->getLMA(); 1344617e2f98SRui Ueyama }; 13452ec34544SRui Ueyama } 1346fa1145a8SIsaac Richter if (tok == "LOG2CEIL") { 1347fa1145a8SIsaac Richter expect("("); 1348fa1145a8SIsaac Richter Expr a = readExpr(); 1349fa1145a8SIsaac Richter expect(")"); 1350fa1145a8SIsaac Richter return [=] { 1351fa1145a8SIsaac Richter // LOG2CEIL(0) is defined to be 0. 1352fa1145a8SIsaac Richter return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1))); 1353fa1145a8SIsaac Richter }; 1354fa1145a8SIsaac Richter } 13553837f427SRui Ueyama if (tok == "MAX" || tok == "MIN") { 1356fd11560fSGeorge Rimar expect("("); 13573837f427SRui Ueyama Expr a = readExpr(); 1358fd11560fSGeorge Rimar expect(","); 13593837f427SRui Ueyama Expr b = readExpr(); 1360fd11560fSGeorge Rimar expect(")"); 13613837f427SRui Ueyama if (tok == "MIN") 13623837f427SRui Ueyama return [=] { return std::min(a().getValue(), b().getValue()); }; 13633837f427SRui Ueyama return [=] { return std::max(a().getValue(), b().getValue()); }; 1364fd11560fSGeorge Rimar } 13653837f427SRui Ueyama if (tok == "ORIGIN") { 13663837f427SRui Ueyama StringRef name = readParenLiteral(); 13673837f427SRui Ueyama if (script->memoryRegions.count(name) == 0) { 13683837f427SRui Ueyama setError("memory region not defined: " + name); 1369b068b037SGeorge Rimar return [] { return 0; }; 1370b068b037SGeorge Rimar } 137192b5b980SFangrui Song return script->memoryRegions[name]->origin; 137291b95b61SRui Ueyama } 13733837f427SRui Ueyama if (tok == "SEGMENT_START") { 13742ec34544SRui Ueyama expect("("); 13752ec34544SRui Ueyama skip(); 13762ec34544SRui Ueyama expect(","); 13773837f427SRui Ueyama Expr e = readExpr(); 13782ec34544SRui Ueyama expect(")"); 13793837f427SRui Ueyama return [=] { return e(); }; 13802ec34544SRui Ueyama } 13813837f427SRui Ueyama if (tok == "SIZEOF") { 13823837f427SRui Ueyama StringRef name = readParenLiteral(); 13833837f427SRui Ueyama OutputSection *cmd = script->getOrCreateOutputSection(name); 138405c4f67cSRafael Espindola // Linker script does not create an output section if its content is empty. 138505c4f67cSRafael Espindola // We want to allow SIZEOF(.foo) where .foo is a section which happened to 138605c4f67cSRafael Espindola // be empty. 13873837f427SRui Ueyama return [=] { return cmd->size; }; 13882ec34544SRui Ueyama } 13893837f427SRui Ueyama if (tok == "SIZEOF_HEADERS") 139007837b8fSFangrui Song return [=] { return elf::getHeaderSize(); }; 13912ec34544SRui Ueyama 13924eb2eccbSRui Ueyama // Tok is the dot. 13933837f427SRui Ueyama if (tok == ".") 13943837f427SRui Ueyama return [=] { return script->getSymbolValue(tok, location); }; 13954eb2eccbSRui Ueyama 13962ec34544SRui Ueyama // Tok is a literal number. 13973837f427SRui Ueyama if (Optional<uint64_t> val = parseInt(tok)) 13983837f427SRui Ueyama return [=] { return *val; }; 13992ec34544SRui Ueyama 14002ec34544SRui Ueyama // Tok is a symbol name. 14013837f427SRui Ueyama if (!isValidCIdentifier(tok)) 14023837f427SRui Ueyama setError("malformed number: " + tok); 14033837f427SRui Ueyama script->referencedSymbols.push_back(tok); 14043837f427SRui Ueyama return [=] { return script->getSymbolValue(tok, location); }; 14052ec34544SRui Ueyama } 14062ec34544SRui Ueyama 14073837f427SRui Ueyama Expr ScriptParser::readTernary(Expr cond) { 14083837f427SRui Ueyama Expr l = readExpr(); 14092ec34544SRui Ueyama expect(":"); 14103837f427SRui Ueyama Expr r = readExpr(); 14113837f427SRui Ueyama return [=] { return cond().getValue() ? l() : r(); }; 14122ec34544SRui Ueyama } 14132ec34544SRui Ueyama 14142ec34544SRui Ueyama Expr ScriptParser::readParenExpr() { 14152ec34544SRui Ueyama expect("("); 14163837f427SRui Ueyama Expr e = readExpr(); 14172ec34544SRui Ueyama expect(")"); 14183837f427SRui Ueyama return e; 14192ec34544SRui Ueyama } 14202ec34544SRui Ueyama 14212ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() { 14223837f427SRui Ueyama std::vector<StringRef> phdrs; 1423b8a59c8aSBob Haarman while (!errorCount() && peek().startswith(":")) { 14243837f427SRui Ueyama StringRef tok = next(); 14253837f427SRui Ueyama phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1)); 14262ec34544SRui Ueyama } 14273837f427SRui Ueyama return phdrs; 14282ec34544SRui Ueyama } 14292ec34544SRui Ueyama 14302ec34544SRui Ueyama // Read a program header type name. The next token must be a 14312ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3"). 14322ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() { 14333837f427SRui Ueyama StringRef tok = next(); 14343837f427SRui Ueyama if (Optional<uint64_t> val = parseInt(tok)) 14353837f427SRui Ueyama return *val; 14362ec34544SRui Ueyama 14373837f427SRui Ueyama unsigned ret = StringSwitch<unsigned>(tok) 14382ec34544SRui Ueyama .Case("PT_NULL", PT_NULL) 14392ec34544SRui Ueyama .Case("PT_LOAD", PT_LOAD) 14402ec34544SRui Ueyama .Case("PT_DYNAMIC", PT_DYNAMIC) 14412ec34544SRui Ueyama .Case("PT_INTERP", PT_INTERP) 14422ec34544SRui Ueyama .Case("PT_NOTE", PT_NOTE) 14432ec34544SRui Ueyama .Case("PT_SHLIB", PT_SHLIB) 14442ec34544SRui Ueyama .Case("PT_PHDR", PT_PHDR) 14452ec34544SRui Ueyama .Case("PT_TLS", PT_TLS) 14462ec34544SRui Ueyama .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 14472ec34544SRui Ueyama .Case("PT_GNU_STACK", PT_GNU_STACK) 14482ec34544SRui Ueyama .Case("PT_GNU_RELRO", PT_GNU_RELRO) 14492ec34544SRui Ueyama .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) 14502ec34544SRui Ueyama .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) 14512ec34544SRui Ueyama .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) 14522ec34544SRui Ueyama .Default(-1); 14532ec34544SRui Ueyama 14543837f427SRui Ueyama if (ret == (unsigned)-1) { 14553837f427SRui Ueyama setError("invalid program header type: " + tok); 14562ec34544SRui Ueyama return PT_NULL; 14572ec34544SRui Ueyama } 14583837f427SRui Ueyama return ret; 14592ec34544SRui Ueyama } 14602ec34544SRui Ueyama 14612ec34544SRui Ueyama // Reads an anonymous version declaration. 14622ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() { 14633837f427SRui Ueyama std::vector<SymbolVersion> locals; 14643837f427SRui Ueyama std::vector<SymbolVersion> globals; 14653837f427SRui Ueyama std::tie(locals, globals) = readSymbols(); 1466e28a70daSFangrui Song for (const SymbolVersion &pat : locals) 1467e28a70daSFangrui Song config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat); 1468e28a70daSFangrui Song for (const SymbolVersion &pat : globals) 1469e28a70daSFangrui Song config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(pat); 14702ec34544SRui Ueyama 14712ec34544SRui Ueyama expect(";"); 14722ec34544SRui Ueyama } 14732ec34544SRui Ueyama 14742ec34544SRui Ueyama // Reads a non-anonymous version definition, 14752ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };". 14763837f427SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef verStr) { 14772ec34544SRui Ueyama // Read a symbol list. 14783837f427SRui Ueyama std::vector<SymbolVersion> locals; 14793837f427SRui Ueyama std::vector<SymbolVersion> globals; 14803837f427SRui Ueyama std::tie(locals, globals) = readSymbols(); 1481e28a70daSFangrui Song for (const SymbolVersion &pat : locals) 1482e28a70daSFangrui Song config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat); 14832ec34544SRui Ueyama 14842ec34544SRui Ueyama // Create a new version definition and add that to the global symbols. 14853837f427SRui Ueyama VersionDefinition ver; 14863837f427SRui Ueyama ver.name = verStr; 1487e28a70daSFangrui Song ver.patterns = globals; 1488e28a70daSFangrui Song ver.id = config->versionDefinitions.size(); 14893837f427SRui Ueyama config->versionDefinitions.push_back(ver); 14902ec34544SRui Ueyama 14912ec34544SRui Ueyama // Each version may have a parent version. For example, "Ver2" 14922ec34544SRui Ueyama // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" 14932ec34544SRui Ueyama // as a parent. This version hierarchy is, probably against your 14942ec34544SRui Ueyama // instinct, purely for hint; the runtime doesn't care about it 14952ec34544SRui Ueyama // at all. In LLD, we simply ignore it. 14965f380403SFangrui Song if (next() != ";") 14972ec34544SRui Ueyama expect(";"); 14982ec34544SRui Ueyama } 14992ec34544SRui Ueyama 150049279ca1SFangrui Song bool elf::hasWildcard(StringRef s) { 15013837f427SRui Ueyama return s.find_first_of("?*[") != StringRef::npos; 15021e77ad14SRui Ueyama } 15031e77ad14SRui Ueyama 15042ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". 15052ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>> 15062ec34544SRui Ueyama ScriptParser::readSymbols() { 15073837f427SRui Ueyama std::vector<SymbolVersion> locals; 15083837f427SRui Ueyama std::vector<SymbolVersion> globals; 15093837f427SRui Ueyama std::vector<SymbolVersion> *v = &globals; 15102ec34544SRui Ueyama 1511b8a59c8aSBob Haarman while (!errorCount()) { 15122ec34544SRui Ueyama if (consume("}")) 15132ec34544SRui Ueyama break; 15142ec34544SRui Ueyama if (consumeLabel("local")) { 15153837f427SRui Ueyama v = &locals; 15162ec34544SRui Ueyama continue; 15172ec34544SRui Ueyama } 15182ec34544SRui Ueyama if (consumeLabel("global")) { 15193837f427SRui Ueyama v = &globals; 15202ec34544SRui Ueyama continue; 15212ec34544SRui Ueyama } 15222ec34544SRui Ueyama 15232ec34544SRui Ueyama if (consume("extern")) { 15243837f427SRui Ueyama std::vector<SymbolVersion> ext = readVersionExtern(); 15253837f427SRui Ueyama v->insert(v->end(), ext.begin(), ext.end()); 15262ec34544SRui Ueyama } else { 15273837f427SRui Ueyama StringRef tok = next(); 15283837f427SRui Ueyama v->push_back({unquote(tok), false, hasWildcard(tok)}); 15292ec34544SRui Ueyama } 15302ec34544SRui Ueyama expect(";"); 15312ec34544SRui Ueyama } 15323837f427SRui Ueyama return {locals, globals}; 15332ec34544SRui Ueyama } 15342ec34544SRui Ueyama 15352ec34544SRui Ueyama // Reads an "extern C++" directive, e.g., 15362ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };" 153717324d8bSRui Ueyama // 153817324d8bSRui Ueyama // The last semicolon is optional. E.g. this is OK: 153917324d8bSRui Ueyama // "extern "C++" { ns::*; "f(int, double)" };" 15402ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() { 15413837f427SRui Ueyama StringRef tok = next(); 15423837f427SRui Ueyama bool isCXX = tok == "\"C++\""; 15433837f427SRui Ueyama if (!isCXX && tok != "\"C\"") 15442ec34544SRui Ueyama setError("Unknown language"); 15452ec34544SRui Ueyama expect("{"); 15462ec34544SRui Ueyama 15473837f427SRui Ueyama std::vector<SymbolVersion> ret; 1548b8a59c8aSBob Haarman while (!errorCount() && peek() != "}") { 15493837f427SRui Ueyama StringRef tok = next(); 15503837f427SRui Ueyama ret.push_back( 15513837f427SRui Ueyama {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)}); 155217324d8bSRui Ueyama if (consume("}")) 15533837f427SRui Ueyama return ret; 15542ec34544SRui Ueyama expect(";"); 15552ec34544SRui Ueyama } 15562ec34544SRui Ueyama 15572ec34544SRui Ueyama expect("}"); 15583837f427SRui Ueyama return ret; 15592ec34544SRui Ueyama } 15602ec34544SRui Ueyama 156192b5b980SFangrui Song Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2, 15623837f427SRui Ueyama StringRef s3) { 15633837f427SRui Ueyama if (!consume(s1) && !consume(s2) && !consume(s3)) { 15643837f427SRui Ueyama setError("expected one of: " + s1 + ", " + s2 + ", or " + s3); 156592b5b980SFangrui Song return [] { return 0; }; 15662ec34544SRui Ueyama } 15672ec34544SRui Ueyama expect("="); 156892b5b980SFangrui Song return readExpr(); 15692ec34544SRui Ueyama } 15702ec34544SRui Ueyama 15712ec34544SRui Ueyama // Parse the MEMORY command as specified in: 15722ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html 15732ec34544SRui Ueyama // 15742ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... } 15752ec34544SRui Ueyama void ScriptParser::readMemory() { 15762ec34544SRui Ueyama expect("{"); 1577b8a59c8aSBob Haarman while (!errorCount() && !consume("}")) { 15783837f427SRui Ueyama StringRef tok = next(); 15793837f427SRui Ueyama if (tok == "INCLUDE") { 15802e9d40d5SRui Ueyama readInclude(); 15812e9d40d5SRui Ueyama continue; 15822e9d40d5SRui Ueyama } 15832ec34544SRui Ueyama 15843837f427SRui Ueyama uint32_t flags = 0; 15853837f427SRui Ueyama uint32_t negFlags = 0; 15862ec34544SRui Ueyama if (consume("(")) { 15873837f427SRui Ueyama std::tie(flags, negFlags) = readMemoryAttributes(); 15882ec34544SRui Ueyama expect(")"); 15892ec34544SRui Ueyama } 15902ec34544SRui Ueyama expect(":"); 15912ec34544SRui Ueyama 159292b5b980SFangrui Song Expr origin = readMemoryAssignment("ORIGIN", "org", "o"); 15932ec34544SRui Ueyama expect(","); 159492b5b980SFangrui Song Expr length = readMemoryAssignment("LENGTH", "len", "l"); 15952ec34544SRui Ueyama 15965f37541cSGeorge Rimar // Add the memory region to the region map. 15973837f427SRui Ueyama MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, negFlags); 15983837f427SRui Ueyama if (!script->memoryRegions.insert({tok, mr}).second) 15993837f427SRui Ueyama setError("region '" + tok + "' already defined"); 16002ec34544SRui Ueyama } 16012ec34544SRui Ueyama } 16022ec34544SRui Ueyama 16032ec34544SRui Ueyama // This function parses the attributes used to match against section 16042ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags 16052ec34544SRui Ueyama // are only used when an explicit memory region name is not used. 16062ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() { 16073837f427SRui Ueyama uint32_t flags = 0; 16083837f427SRui Ueyama uint32_t negFlags = 0; 16093837f427SRui Ueyama bool invert = false; 16102ec34544SRui Ueyama 16113837f427SRui Ueyama for (char c : next().lower()) { 16123837f427SRui Ueyama uint32_t flag = 0; 16133837f427SRui Ueyama if (c == '!') 16143837f427SRui Ueyama invert = !invert; 16153837f427SRui Ueyama else if (c == 'w') 16163837f427SRui Ueyama flag = SHF_WRITE; 16173837f427SRui Ueyama else if (c == 'x') 16183837f427SRui Ueyama flag = SHF_EXECINSTR; 16193837f427SRui Ueyama else if (c == 'a') 16203837f427SRui Ueyama flag = SHF_ALLOC; 16213837f427SRui Ueyama else if (c != 'r') 16222ec34544SRui Ueyama setError("invalid memory region attribute"); 16232ec34544SRui Ueyama 16243837f427SRui Ueyama if (invert) 16253837f427SRui Ueyama negFlags |= flag; 16262ec34544SRui Ueyama else 16273837f427SRui Ueyama flags |= flag; 16282ec34544SRui Ueyama } 16293837f427SRui Ueyama return {flags, negFlags}; 16302ec34544SRui Ueyama } 16312ec34544SRui Ueyama 163207837b8fSFangrui Song void elf::readLinkerScript(MemoryBufferRef mb) { 1633439341b9SJames Henderson llvm::TimeTraceScope timeScope("Read linker script", 1634439341b9SJames Henderson mb.getBufferIdentifier()); 16353837f427SRui Ueyama ScriptParser(mb).readLinkerScript(); 16362ec34544SRui Ueyama } 16372ec34544SRui Ueyama 163807837b8fSFangrui Song void elf::readVersionScript(MemoryBufferRef mb) { 1639439341b9SJames Henderson llvm::TimeTraceScope timeScope("Read version script", 1640439341b9SJames Henderson mb.getBufferIdentifier()); 16413837f427SRui Ueyama ScriptParser(mb).readVersionScript(); 16422ec34544SRui Ueyama } 16432ec34544SRui Ueyama 164407837b8fSFangrui Song void elf::readDynamicList(MemoryBufferRef mb) { 1645439341b9SJames Henderson llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier()); 164607837b8fSFangrui Song ScriptParser(mb).readDynamicList(); 16478c7e8cceSPetr Hosek } 1648bd8cfe65SFangrui Song 164907837b8fSFangrui Song void elf::readDefsym(StringRef name, MemoryBufferRef mb) { 1650439341b9SJames Henderson llvm::TimeTraceScope timeScope("Read defsym input", name); 165107837b8fSFangrui Song ScriptParser(mb).readDefsym(name); 165207837b8fSFangrui Song } 1653