Path: blob/main/contrib/llvm-project/lld/ELF/ScriptParser.cpp
34878 views
//===- ScriptParser.cpp ---------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains a recursive-descendent parser for linker scripts.9// Parsed results are stored to Config and Script global objects.10//11//===----------------------------------------------------------------------===//1213#include "ScriptParser.h"14#include "Config.h"15#include "Driver.h"16#include "InputFiles.h"17#include "LinkerScript.h"18#include "OutputSections.h"19#include "ScriptLexer.h"20#include "SymbolTable.h"21#include "Symbols.h"22#include "Target.h"23#include "lld/Common/CommonLinkerContext.h"24#include "llvm/ADT/SmallString.h"25#include "llvm/ADT/StringRef.h"26#include "llvm/ADT/StringSet.h"27#include "llvm/ADT/StringSwitch.h"28#include "llvm/BinaryFormat/ELF.h"29#include "llvm/Support/Casting.h"30#include "llvm/Support/ErrorHandling.h"31#include "llvm/Support/FileSystem.h"32#include "llvm/Support/MathExtras.h"33#include "llvm/Support/Path.h"34#include "llvm/Support/SaveAndRestore.h"35#include "llvm/Support/TimeProfiler.h"36#include <cassert>37#include <limits>38#include <optional>39#include <vector>4041using namespace llvm;42using namespace llvm::ELF;43using namespace llvm::support::endian;44using namespace lld;45using namespace lld::elf;4647namespace {48class ScriptParser final : ScriptLexer {49public:50ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) {51// Initialize IsUnderSysroot52if (config->sysroot == "")53return;54StringRef path = mb.getBufferIdentifier();55for (; !path.empty(); path = sys::path::parent_path(path)) {56if (!sys::fs::equivalent(config->sysroot, path))57continue;58isUnderSysroot = true;59return;60}61}6263void readLinkerScript();64void readVersionScript();65void readDynamicList();66void readDefsym(StringRef name);6768private:69void addFile(StringRef path);7071void readAsNeeded();72void readEntry();73void readExtern();74void readGroup();75void readInclude();76void readInput();77void readMemory();78void readOutput();79void readOutputArch();80void readOutputFormat();81void readOverwriteSections();82void readPhdrs();83void readRegionAlias();84void readSearchDir();85void readSections();86void readTarget();87void readVersion();88void readVersionScriptCommand();89void readNoCrossRefs(bool to);9091SymbolAssignment *readSymbolAssignment(StringRef name);92ByteCommand *readByteCommand(StringRef tok);93std::array<uint8_t, 4> readFill();94bool readSectionDirective(OutputSection *cmd, StringRef tok);95void readSectionAddressType(OutputSection *cmd);96OutputDesc *readOverlaySectionDescription();97OutputDesc *readOutputSectionDescription(StringRef outSec);98SmallVector<SectionCommand *, 0> readOverlay();99SmallVector<StringRef, 0> readOutputSectionPhdrs();100std::pair<uint64_t, uint64_t> readInputSectionFlags();101InputSectionDescription *readInputSectionDescription(StringRef tok);102StringMatcher readFilePatterns();103SmallVector<SectionPattern, 0> readInputSectionsList();104InputSectionDescription *readInputSectionRules(StringRef filePattern,105uint64_t withFlags,106uint64_t withoutFlags);107unsigned readPhdrType();108SortSectionPolicy peekSortKind();109SortSectionPolicy readSortKind();110SymbolAssignment *readProvideHidden(bool provide, bool hidden);111SymbolAssignment *readAssignment(StringRef tok);112void readSort();113Expr readAssert();114Expr readConstant();115Expr getPageSize();116117Expr readMemoryAssignment(StringRef, StringRef, StringRef);118void readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,119uint32_t &negFlags, uint32_t &negInvFlags);120121Expr combine(StringRef op, Expr l, Expr r);122Expr readExpr();123Expr readExpr1(Expr lhs, int minPrec);124StringRef readParenLiteral();125Expr readPrimary();126Expr readTernary(Expr cond);127Expr readParenExpr();128129// For parsing version script.130SmallVector<SymbolVersion, 0> readVersionExtern();131void readAnonymousDeclaration();132void readVersionDeclaration(StringRef verStr);133134std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>135readSymbols();136137// True if a script being read is in the --sysroot directory.138bool isUnderSysroot = false;139140// A set to detect an INCLUDE() cycle.141StringSet<> seen;142143// If we are currently parsing a PROVIDE|PROVIDE_HIDDEN command,144// then this member is set to the PROVIDE symbol name.145std::optional<llvm::StringRef> activeProvideSym;146};147} // namespace148149static StringRef unquote(StringRef s) {150if (s.starts_with("\""))151return s.substr(1, s.size() - 2);152return s;153}154155// Some operations only support one non absolute value. Move the156// absolute one to the right hand side for convenience.157static void moveAbsRight(ExprValue &a, ExprValue &b) {158if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))159std::swap(a, b);160if (!b.isAbsolute())161script->recordError(162a.loc + ": at least one side of the expression must be absolute");163}164165static ExprValue add(ExprValue a, ExprValue b) {166moveAbsRight(a, b);167return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};168}169170static ExprValue sub(ExprValue a, ExprValue b) {171// The distance between two symbols in sections is absolute.172if (!a.isAbsolute() && !b.isAbsolute())173return a.getValue() - b.getValue();174return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};175}176177static ExprValue bitAnd(ExprValue a, ExprValue b) {178moveAbsRight(a, b);179return {a.sec, a.forceAbsolute,180(a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};181}182183static ExprValue bitXor(ExprValue a, ExprValue b) {184moveAbsRight(a, b);185return {a.sec, a.forceAbsolute,186(a.getValue() ^ b.getValue()) - a.getSecAddr(), a.loc};187}188189static ExprValue bitOr(ExprValue a, ExprValue b) {190moveAbsRight(a, b);191return {a.sec, a.forceAbsolute,192(a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};193}194195void ScriptParser::readDynamicList() {196expect("{");197SmallVector<SymbolVersion, 0> locals;198SmallVector<SymbolVersion, 0> globals;199std::tie(locals, globals) = readSymbols();200expect(";");201202if (!atEOF()) {203setError("EOF expected, but got " + next());204return;205}206if (!locals.empty()) {207setError("\"local:\" scope not supported in --dynamic-list");208return;209}210211for (SymbolVersion v : globals)212config->dynamicList.push_back(v);213}214215void ScriptParser::readVersionScript() {216readVersionScriptCommand();217if (!atEOF())218setError("EOF expected, but got " + next());219}220221void ScriptParser::readVersionScriptCommand() {222if (consume("{")) {223readAnonymousDeclaration();224return;225}226227while (!atEOF() && !errorCount() && peek() != "}") {228StringRef verStr = next();229if (verStr == "{") {230setError("anonymous version definition is used in "231"combination with other version definitions");232return;233}234expect("{");235readVersionDeclaration(verStr);236}237}238239void ScriptParser::readVersion() {240expect("{");241readVersionScriptCommand();242expect("}");243}244245void ScriptParser::readLinkerScript() {246while (!atEOF()) {247StringRef tok = next();248if (tok == ";")249continue;250251if (tok == "ENTRY") {252readEntry();253} else if (tok == "EXTERN") {254readExtern();255} else if (tok == "GROUP") {256readGroup();257} else if (tok == "INCLUDE") {258readInclude();259} else if (tok == "INPUT") {260readInput();261} else if (tok == "MEMORY") {262readMemory();263} else if (tok == "OUTPUT") {264readOutput();265} else if (tok == "OUTPUT_ARCH") {266readOutputArch();267} else if (tok == "OUTPUT_FORMAT") {268readOutputFormat();269} else if (tok == "OVERWRITE_SECTIONS") {270readOverwriteSections();271} else if (tok == "PHDRS") {272readPhdrs();273} else if (tok == "REGION_ALIAS") {274readRegionAlias();275} else if (tok == "SEARCH_DIR") {276readSearchDir();277} else if (tok == "SECTIONS") {278readSections();279} else if (tok == "TARGET") {280readTarget();281} else if (tok == "VERSION") {282readVersion();283} else if (tok == "NOCROSSREFS") {284readNoCrossRefs(/*to=*/false);285} else if (tok == "NOCROSSREFS_TO") {286readNoCrossRefs(/*to=*/true);287} else if (SymbolAssignment *cmd = readAssignment(tok)) {288script->sectionCommands.push_back(cmd);289} else {290setError("unknown directive: " + tok);291}292}293}294295void ScriptParser::readDefsym(StringRef name) {296if (errorCount())297return;298Expr e = readExpr();299if (!atEOF())300setError("EOF expected, but got " + next());301auto *cmd = make<SymbolAssignment>(302name, e, 0, getCurrentMB().getBufferIdentifier().str());303script->sectionCommands.push_back(cmd);304}305306void ScriptParser::readNoCrossRefs(bool to) {307expect("(");308NoCrossRefCommand cmd{{}, to};309while (!errorCount() && !consume(")"))310cmd.outputSections.push_back(unquote(next()));311if (cmd.outputSections.size() < 2)312warn(getCurrentLocation() + ": ignored with fewer than 2 output sections");313else314script->noCrossRefs.push_back(std::move(cmd));315}316317void ScriptParser::addFile(StringRef s) {318if (isUnderSysroot && s.starts_with("/")) {319SmallString<128> pathData;320StringRef path = (config->sysroot + s).toStringRef(pathData);321if (sys::fs::exists(path))322ctx.driver.addFile(saver().save(path), /*withLOption=*/false);323else324setError("cannot find " + s + " inside " + config->sysroot);325return;326}327328if (s.starts_with("/")) {329// Case 1: s is an absolute path. Just open it.330ctx.driver.addFile(s, /*withLOption=*/false);331} else if (s.starts_with("=")) {332// Case 2: relative to the sysroot.333if (config->sysroot.empty())334ctx.driver.addFile(s.substr(1), /*withLOption=*/false);335else336ctx.driver.addFile(saver().save(config->sysroot + "/" + s.substr(1)),337/*withLOption=*/false);338} else if (s.starts_with("-l")) {339// Case 3: search in the list of library paths.340ctx.driver.addLibrary(s.substr(2));341} else {342// Case 4: s is a relative path. Search in the directory of the script file.343std::string filename = std::string(getCurrentMB().getBufferIdentifier());344StringRef directory = sys::path::parent_path(filename);345if (!directory.empty()) {346SmallString<0> path(directory);347sys::path::append(path, s);348if (sys::fs::exists(path)) {349ctx.driver.addFile(path, /*withLOption=*/false);350return;351}352}353// Then search in the current working directory.354if (sys::fs::exists(s)) {355ctx.driver.addFile(s, /*withLOption=*/false);356} else {357// Finally, search in the list of library paths.358if (std::optional<std::string> path = findFromSearchPaths(s))359ctx.driver.addFile(saver().save(*path), /*withLOption=*/true);360else361setError("unable to find " + s);362}363}364}365366void ScriptParser::readAsNeeded() {367expect("(");368bool orig = config->asNeeded;369config->asNeeded = true;370while (!errorCount() && !consume(")"))371addFile(unquote(next()));372config->asNeeded = orig;373}374375void ScriptParser::readEntry() {376// -e <symbol> takes predecence over ENTRY(<symbol>).377expect("(");378StringRef tok = next();379if (config->entry.empty())380config->entry = unquote(tok);381expect(")");382}383384void ScriptParser::readExtern() {385expect("(");386while (!errorCount() && !consume(")"))387config->undefined.push_back(unquote(next()));388}389390void ScriptParser::readGroup() {391bool orig = InputFile::isInGroup;392InputFile::isInGroup = true;393readInput();394InputFile::isInGroup = orig;395if (!orig)396++InputFile::nextGroupId;397}398399void ScriptParser::readInclude() {400StringRef tok = unquote(next());401402if (!seen.insert(tok).second) {403setError("there is a cycle in linker script INCLUDEs");404return;405}406407if (std::optional<std::string> path = searchScript(tok)) {408if (std::optional<MemoryBufferRef> mb = readFile(*path))409tokenize(*mb);410return;411}412setError("cannot find linker script " + tok);413}414415void ScriptParser::readInput() {416expect("(");417while (!errorCount() && !consume(")")) {418if (consume("AS_NEEDED"))419readAsNeeded();420else421addFile(unquote(next()));422}423}424425void ScriptParser::readOutput() {426// -o <file> takes predecence over OUTPUT(<file>).427expect("(");428StringRef tok = next();429if (config->outputFile.empty())430config->outputFile = unquote(tok);431expect(")");432}433434void ScriptParser::readOutputArch() {435// OUTPUT_ARCH is ignored for now.436expect("(");437while (!errorCount() && !consume(")"))438skip();439}440441static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {442return StringSwitch<std::pair<ELFKind, uint16_t>>(s)443.Case("elf32-i386", {ELF32LEKind, EM_386})444.Case("elf32-avr", {ELF32LEKind, EM_AVR})445.Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})446.Case("elf32-littlearm", {ELF32LEKind, EM_ARM})447.Case("elf32-bigarm", {ELF32BEKind, EM_ARM})448.Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})449.Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})450.Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})451.Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64})452.Case("elf32-powerpc", {ELF32BEKind, EM_PPC})453.Case("elf32-powerpcle", {ELF32LEKind, EM_PPC})454.Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})455.Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})456.Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})457.Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})458.Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})459.Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})460.Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})461.Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})462.Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})463.Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})464.Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})465.Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9})466.Case("elf32-msp430", {ELF32LEKind, EM_MSP430})467.Case("elf32-loongarch", {ELF32LEKind, EM_LOONGARCH})468.Case("elf64-loongarch", {ELF64LEKind, EM_LOONGARCH})469.Case("elf64-s390", {ELF64BEKind, EM_S390})470.Cases("elf32-hexagon", "elf32-littlehexagon", {ELF32LEKind, EM_HEXAGON})471.Default({ELFNoneKind, EM_NONE});472}473474// Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose475// big if -EB is specified, little if -EL is specified, or default if neither is476// specified.477void ScriptParser::readOutputFormat() {478expect("(");479480StringRef s = unquote(next());481if (!consume(")")) {482expect(",");483StringRef tmp = unquote(next());484if (config->optEB)485s = tmp;486expect(",");487tmp = unquote(next());488if (config->optEL)489s = tmp;490consume(")");491}492// If more than one OUTPUT_FORMAT is specified, only the first is checked.493if (!config->bfdname.empty())494return;495config->bfdname = s;496497if (s == "binary") {498config->oFormatBinary = true;499return;500}501502if (s.consume_back("-freebsd"))503config->osabi = ELFOSABI_FREEBSD;504505std::tie(config->ekind, config->emachine) = parseBfdName(s);506if (config->emachine == EM_NONE)507setError("unknown output format name: " + config->bfdname);508if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")509config->mipsN32Abi = true;510if (config->emachine == EM_MSP430)511config->osabi = ELFOSABI_STANDALONE;512}513514void ScriptParser::readPhdrs() {515expect("{");516517while (!errorCount() && !consume("}")) {518PhdrsCommand cmd;519cmd.name = next();520cmd.type = readPhdrType();521522while (!errorCount() && !consume(";")) {523if (consume("FILEHDR"))524cmd.hasFilehdr = true;525else if (consume("PHDRS"))526cmd.hasPhdrs = true;527else if (consume("AT"))528cmd.lmaExpr = readParenExpr();529else if (consume("FLAGS"))530cmd.flags = readParenExpr()().getValue();531else532setError("unexpected header attribute: " + next());533}534535script->phdrsCommands.push_back(cmd);536}537}538539void ScriptParser::readRegionAlias() {540expect("(");541StringRef alias = unquote(next());542expect(",");543StringRef name = next();544expect(")");545546if (script->memoryRegions.count(alias))547setError("redefinition of memory region '" + alias + "'");548if (!script->memoryRegions.count(name))549setError("memory region '" + name + "' is not defined");550script->memoryRegions.insert({alias, script->memoryRegions[name]});551}552553void ScriptParser::readSearchDir() {554expect("(");555StringRef tok = next();556if (!config->nostdlib)557config->searchPaths.push_back(unquote(tok));558expect(")");559}560561// This reads an overlay description. Overlays are used to describe output562// sections that use the same virtual memory range and normally would trigger563// linker's sections sanity check failures.564// https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description565SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() {566Expr addrExpr;567if (consume(":")) {568addrExpr = [] { return script->getDot(); };569} else {570addrExpr = readExpr();571expect(":");572}573// When AT is omitted, LMA should equal VMA. script->getDot() when evaluating574// lmaExpr will ensure this, even if the start address is specified.575Expr lmaExpr =576consume("AT") ? readParenExpr() : [] { return script->getDot(); };577expect("{");578579SmallVector<SectionCommand *, 0> v;580OutputSection *prev = nullptr;581while (!errorCount() && !consume("}")) {582// VA is the same for all sections. The LMAs are consecutive in memory583// starting from the base load address specified.584OutputDesc *osd = readOverlaySectionDescription();585osd->osec.addrExpr = addrExpr;586if (prev) {587osd->osec.lmaExpr = [=] { return prev->getLMA() + prev->size; };588} else {589osd->osec.lmaExpr = lmaExpr;590// Use first section address for subsequent sections as initial addrExpr591// can be DOT. Ensure the first section, even if empty, is not discarded.592osd->osec.usedInExpression = true;593addrExpr = [=]() -> ExprValue { return {&osd->osec, false, 0, ""}; };594}595v.push_back(osd);596prev = &osd->osec;597}598599// According to the specification, at the end of the overlay, the location600// counter should be equal to the overlay base address plus size of the601// largest section seen in the overlay.602// Here we want to create the Dot assignment command to achieve that.603Expr moveDot = [=] {604uint64_t max = 0;605for (SectionCommand *cmd : v)606max = std::max(max, cast<OutputDesc>(cmd)->osec.size);607return addrExpr().getValue() + max;608};609v.push_back(make<SymbolAssignment>(".", moveDot, 0, getCurrentLocation()));610return v;611}612613void ScriptParser::readOverwriteSections() {614expect("{");615while (!errorCount() && !consume("}"))616script->overwriteSections.push_back(readOutputSectionDescription(next()));617}618619void ScriptParser::readSections() {620expect("{");621SmallVector<SectionCommand *, 0> v;622while (!errorCount() && !consume("}")) {623StringRef tok = next();624if (tok == "OVERLAY") {625for (SectionCommand *cmd : readOverlay())626v.push_back(cmd);627continue;628} else if (tok == "INCLUDE") {629readInclude();630continue;631}632633if (SectionCommand *cmd = readAssignment(tok))634v.push_back(cmd);635else636v.push_back(readOutputSectionDescription(tok));637}638639// If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN,640// the relro fields should be cleared.641if (!script->seenRelroEnd)642for (SectionCommand *cmd : v)643if (auto *osd = dyn_cast<OutputDesc>(cmd))644osd->osec.relro = false;645646script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),647v.end());648649if (atEOF() || !consume("INSERT")) {650script->hasSectionsCommand = true;651return;652}653654bool isAfter = false;655if (consume("AFTER"))656isAfter = true;657else if (!consume("BEFORE"))658setError("expected AFTER/BEFORE, but got '" + next() + "'");659StringRef where = next();660SmallVector<StringRef, 0> names;661for (SectionCommand *cmd : v)662if (auto *os = dyn_cast<OutputDesc>(cmd))663names.push_back(os->osec.name);664if (!names.empty())665script->insertCommands.push_back({std::move(names), isAfter, where});666}667668void ScriptParser::readTarget() {669// TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,670// we accept only a limited set of BFD names (i.e. "elf" or "binary")671// for --format. We recognize only /^elf/ and "binary" in the linker672// script as well.673expect("(");674StringRef tok = unquote(next());675expect(")");676677if (tok.starts_with("elf"))678config->formatBinary = false;679else if (tok == "binary")680config->formatBinary = true;681else682setError("unknown target: " + tok);683}684685static int precedence(StringRef op) {686return StringSwitch<int>(op)687.Cases("*", "/", "%", 11)688.Cases("+", "-", 10)689.Cases("<<", ">>", 9)690.Cases("<", "<=", ">", ">=", 8)691.Cases("==", "!=", 7)692.Case("&", 6)693.Case("^", 5)694.Case("|", 4)695.Case("&&", 3)696.Case("||", 2)697.Case("?", 1)698.Default(-1);699}700701StringMatcher ScriptParser::readFilePatterns() {702StringMatcher Matcher;703704while (!errorCount() && !consume(")"))705Matcher.addPattern(SingleStringMatcher(next()));706return Matcher;707}708709SortSectionPolicy ScriptParser::peekSortKind() {710return StringSwitch<SortSectionPolicy>(peek())711.Case("REVERSE", SortSectionPolicy::Reverse)712.Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)713.Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)714.Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)715.Case("SORT_NONE", SortSectionPolicy::None)716.Default(SortSectionPolicy::Default);717}718719SortSectionPolicy ScriptParser::readSortKind() {720SortSectionPolicy ret = peekSortKind();721if (ret != SortSectionPolicy::Default)722skip();723return ret;724}725726// Reads SECTIONS command contents in the following form:727//728// <contents> ::= <elem>*729// <elem> ::= <exclude>? <glob-pattern>730// <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"731//732// For example,733//734// *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)735//736// is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".737// The semantics of that is section .foo in any file, section .bar in738// any file but a.o, and section .baz in any file but b.o.739SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() {740SmallVector<SectionPattern, 0> ret;741while (!errorCount() && peek() != ")") {742StringMatcher excludeFilePat;743if (consume("EXCLUDE_FILE")) {744expect("(");745excludeFilePat = readFilePatterns();746}747748StringMatcher SectionMatcher;749// Break if the next token is ), EXCLUDE_FILE, or SORT*.750while (!errorCount() && peekSortKind() == SortSectionPolicy::Default) {751StringRef s = peek();752if (s == ")" || s == "EXCLUDE_FILE")753break;754// Detect common mistakes when certain non-wildcard meta characters are755// used without a closing ')'.756if (!s.empty() && strchr("(){}", s[0])) {757skip();758setError("section pattern is expected");759break;760}761SectionMatcher.addPattern(unquote(next()));762}763764if (!SectionMatcher.empty())765ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});766else if (excludeFilePat.empty())767break;768else769setError("section pattern is expected");770}771return ret;772}773774// Reads contents of "SECTIONS" directive. That directive contains a775// list of glob patterns for input sections. The grammar is as follows.776//777// <patterns> ::= <section-list>778// | <sort> "(" <section-list> ")"779// | <sort> "(" <sort> "(" <section-list> ")" ")"780//781// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"782// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"783//784// <section-list> is parsed by readInputSectionsList().785InputSectionDescription *786ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,787uint64_t withoutFlags) {788auto *cmd =789make<InputSectionDescription>(filePattern, withFlags, withoutFlags);790expect("(");791792while (!errorCount() && !consume(")")) {793SortSectionPolicy outer = readSortKind();794SortSectionPolicy inner = SortSectionPolicy::Default;795SmallVector<SectionPattern, 0> v;796if (outer != SortSectionPolicy::Default) {797expect("(");798inner = readSortKind();799if (inner != SortSectionPolicy::Default) {800expect("(");801v = readInputSectionsList();802expect(")");803} else {804v = readInputSectionsList();805}806expect(")");807} else {808v = readInputSectionsList();809}810811for (SectionPattern &pat : v) {812pat.sortInner = inner;813pat.sortOuter = outer;814}815816std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));817}818return cmd;819}820821InputSectionDescription *822ScriptParser::readInputSectionDescription(StringRef tok) {823// Input section wildcard can be surrounded by KEEP.824// https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep825uint64_t withFlags = 0;826uint64_t withoutFlags = 0;827if (tok == "KEEP") {828expect("(");829if (consume("INPUT_SECTION_FLAGS"))830std::tie(withFlags, withoutFlags) = readInputSectionFlags();831InputSectionDescription *cmd =832readInputSectionRules(next(), withFlags, withoutFlags);833expect(")");834script->keptSections.push_back(cmd);835return cmd;836}837if (tok == "INPUT_SECTION_FLAGS") {838std::tie(withFlags, withoutFlags) = readInputSectionFlags();839tok = next();840}841return readInputSectionRules(tok, withFlags, withoutFlags);842}843844void ScriptParser::readSort() {845expect("(");846expect("CONSTRUCTORS");847expect(")");848}849850Expr ScriptParser::readAssert() {851expect("(");852Expr e = readExpr();853expect(",");854StringRef msg = unquote(next());855expect(")");856857return [=] {858if (!e().getValue())859errorOrWarn(msg);860return script->getDot();861};862}863864#define ECase(X) \865{ #X, X }866constexpr std::pair<const char *, unsigned> typeMap[] = {867ECase(SHT_PROGBITS), ECase(SHT_NOTE), ECase(SHT_NOBITS),868ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY),869};870#undef ECase871872// Tries to read the special directive for an output section definition which873// can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and874// "(TYPE=<value>)".875bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok) {876if (tok != "NOLOAD" && tok != "COPY" && tok != "INFO" && tok != "OVERLAY" &&877tok != "TYPE")878return false;879880if (consume("NOLOAD")) {881cmd->type = SHT_NOBITS;882cmd->typeIsSet = true;883} else if (consume("TYPE")) {884expect("=");885StringRef value = peek();886auto it = llvm::find_if(typeMap, [=](auto e) { return e.first == value; });887if (it != std::end(typeMap)) {888// The value is a recognized literal SHT_*.889cmd->type = it->second;890skip();891} else if (value.starts_with("SHT_")) {892setError("unknown section type " + value);893} else {894// Otherwise, read an expression.895cmd->type = readExpr()().getValue();896}897cmd->typeIsSet = true;898} else {899skip(); // This is "COPY", "INFO" or "OVERLAY".900cmd->nonAlloc = true;901}902expect(")");903return true;904}905906// Reads an expression and/or the special directive for an output907// section definition. Directive is one of following: "(NOLOAD)",908// "(COPY)", "(INFO)" or "(OVERLAY)".909//910// An output section name can be followed by an address expression911// and/or directive. This grammar is not LL(1) because "(" can be912// interpreted as either the beginning of some expression or beginning913// of directive.914//915// https://sourceware.org/binutils/docs/ld/Output-Section-Address.html916// https://sourceware.org/binutils/docs/ld/Output-Section-Type.html917void ScriptParser::readSectionAddressType(OutputSection *cmd) {918if (consume("(")) {919// Temporarily set inExpr to support TYPE=<value> without spaces.920SaveAndRestore saved(inExpr, true);921if (readSectionDirective(cmd, peek()))922return;923cmd->addrExpr = readExpr();924expect(")");925} else {926cmd->addrExpr = readExpr();927}928929if (consume("(")) {930SaveAndRestore saved(inExpr, true);931StringRef tok = peek();932if (!readSectionDirective(cmd, tok))933setError("unknown section directive: " + tok);934}935}936937static Expr checkAlignment(Expr e, std::string &loc) {938return [=] {939uint64_t alignment = std::max((uint64_t)1, e().getValue());940if (!isPowerOf2_64(alignment)) {941error(loc + ": alignment must be power of 2");942return (uint64_t)1; // Return a dummy value.943}944return alignment;945};946}947948OutputDesc *ScriptParser::readOverlaySectionDescription() {949OutputDesc *osd = script->createOutputSection(next(), getCurrentLocation());950osd->osec.inOverlay = true;951expect("{");952while (!errorCount() && !consume("}")) {953uint64_t withFlags = 0;954uint64_t withoutFlags = 0;955if (consume("INPUT_SECTION_FLAGS"))956std::tie(withFlags, withoutFlags) = readInputSectionFlags();957osd->osec.commands.push_back(958readInputSectionRules(next(), withFlags, withoutFlags));959}960osd->osec.phdrs = readOutputSectionPhdrs();961return osd;962}963964OutputDesc *ScriptParser::readOutputSectionDescription(StringRef outSec) {965OutputDesc *cmd =966script->createOutputSection(unquote(outSec), getCurrentLocation());967OutputSection *osec = &cmd->osec;968// Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.969osec->relro = script->seenDataAlign && !script->seenRelroEnd;970971size_t symbolsReferenced = script->referencedSymbols.size();972973if (peek() != ":")974readSectionAddressType(osec);975expect(":");976977std::string location = getCurrentLocation();978if (consume("AT"))979osec->lmaExpr = readParenExpr();980if (consume("ALIGN"))981osec->alignExpr = checkAlignment(readParenExpr(), location);982if (consume("SUBALIGN"))983osec->subalignExpr = checkAlignment(readParenExpr(), location);984985// Parse constraints.986if (consume("ONLY_IF_RO"))987osec->constraint = ConstraintKind::ReadOnly;988if (consume("ONLY_IF_RW"))989osec->constraint = ConstraintKind::ReadWrite;990expect("{");991992while (!errorCount() && !consume("}")) {993StringRef tok = next();994if (tok == ";") {995// Empty commands are allowed. Do nothing here.996} else if (SymbolAssignment *assign = readAssignment(tok)) {997osec->commands.push_back(assign);998} else if (ByteCommand *data = readByteCommand(tok)) {999osec->commands.push_back(data);1000} else if (tok == "CONSTRUCTORS") {1001// CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors1002// by name. This is for very old file formats such as ECOFF/XCOFF.1003// For ELF, we should ignore.1004} else if (tok == "FILL") {1005// We handle the FILL command as an alias for =fillexp section attribute,1006// which is different from what GNU linkers do.1007// https://sourceware.org/binutils/docs/ld/Output-Section-Data.html1008if (peek() != "(")1009setError("( expected, but got " + peek());1010osec->filler = readFill();1011} else if (tok == "SORT") {1012readSort();1013} else if (tok == "INCLUDE") {1014readInclude();1015} else if (tok == "(" || tok == ")") {1016setError("expected filename pattern");1017} else if (peek() == "(") {1018osec->commands.push_back(readInputSectionDescription(tok));1019} else {1020// We have a file name and no input sections description. It is not a1021// commonly used syntax, but still acceptable. In that case, all sections1022// from the file will be included.1023// FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not1024// handle this case here as it will already have been matched by the1025// case above.1026auto *isd = make<InputSectionDescription>(tok);1027isd->sectionPatterns.push_back({{}, StringMatcher("*")});1028osec->commands.push_back(isd);1029}1030}10311032if (consume(">"))1033osec->memoryRegionName = std::string(next());10341035if (consume("AT")) {1036expect(">");1037osec->lmaRegionName = std::string(next());1038}10391040if (osec->lmaExpr && !osec->lmaRegionName.empty())1041error("section can't have both LMA and a load region");10421043osec->phdrs = readOutputSectionPhdrs();10441045if (peek() == "=" || peek().starts_with("=")) {1046inExpr = true;1047consume("=");1048osec->filler = readFill();1049inExpr = false;1050}10511052// Consume optional comma following output section command.1053consume(",");10541055if (script->referencedSymbols.size() > symbolsReferenced)1056osec->expressionsUseSymbols = true;1057return cmd;1058}10591060// Reads a `=<fillexp>` expression and returns its value as a big-endian number.1061// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html1062// We do not support using symbols in such expressions.1063//1064// When reading a hexstring, ld.bfd handles it as a blob of arbitrary1065// size, while ld.gold always handles it as a 32-bit big-endian number.1066// We are compatible with ld.gold because it's easier to implement.1067// Also, we require that expressions with operators must be wrapped into1068// round brackets. We did it to resolve the ambiguity when parsing scripts like:1069// SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }1070std::array<uint8_t, 4> ScriptParser::readFill() {1071uint64_t value = readPrimary()().val;1072if (value > UINT32_MAX)1073setError("filler expression result does not fit 32-bit: 0x" +1074Twine::utohexstr(value));10751076std::array<uint8_t, 4> buf;1077write32be(buf.data(), (uint32_t)value);1078return buf;1079}10801081SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {1082expect("(");1083StringRef name = next(), eq = peek();1084if (eq != "=") {1085setError("= expected, but got " + next());1086while (!atEOF() && next() != ")")1087;1088return nullptr;1089}1090llvm::SaveAndRestore saveActiveProvideSym(activeProvideSym);1091if (provide)1092activeProvideSym = name;1093SymbolAssignment *cmd = readSymbolAssignment(name);1094cmd->provide = provide;1095cmd->hidden = hidden;1096expect(")");1097return cmd;1098}10991100SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {1101// Assert expression returns Dot, so this is equal to ".=."1102if (tok == "ASSERT")1103return make<SymbolAssignment>(".", readAssert(), 0, getCurrentLocation());11041105size_t oldPos = pos;1106SymbolAssignment *cmd = nullptr;1107bool savedSeenRelroEnd = script->seenRelroEnd;1108const StringRef op = peek();1109if (op.starts_with("=")) {1110// Support = followed by an expression without whitespace.1111SaveAndRestore saved(inExpr, true);1112cmd = readSymbolAssignment(tok);1113} else if ((op.size() == 2 && op[1] == '=' && strchr("*/+-&^|", op[0])) ||1114op == "<<=" || op == ">>=") {1115cmd = readSymbolAssignment(tok);1116} else if (tok == "PROVIDE") {1117SaveAndRestore saved(inExpr, true);1118cmd = readProvideHidden(true, false);1119} else if (tok == "HIDDEN") {1120SaveAndRestore saved(inExpr, true);1121cmd = readProvideHidden(false, true);1122} else if (tok == "PROVIDE_HIDDEN") {1123SaveAndRestore saved(inExpr, true);1124cmd = readProvideHidden(true, true);1125}11261127if (cmd) {1128cmd->dataSegmentRelroEnd = !savedSeenRelroEnd && script->seenRelroEnd;1129cmd->commandString =1130tok.str() + " " +1131llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");1132expect(";");1133}1134return cmd;1135}11361137SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {1138name = unquote(name);1139StringRef op = next();1140assert(op == "=" || op == "*=" || op == "/=" || op == "+=" || op == "-=" ||1141op == "&=" || op == "^=" || op == "|=" || op == "<<=" || op == ">>=");1142// Note: GNU ld does not support %=.1143Expr e = readExpr();1144if (op != "=") {1145std::string loc = getCurrentLocation();1146e = [=, c = op[0]]() -> ExprValue {1147ExprValue lhs = script->getSymbolValue(name, loc);1148switch (c) {1149case '*':1150return lhs.getValue() * e().getValue();1151case '/':1152if (uint64_t rv = e().getValue())1153return lhs.getValue() / rv;1154error(loc + ": division by zero");1155return 0;1156case '+':1157return add(lhs, e());1158case '-':1159return sub(lhs, e());1160case '<':1161return lhs.getValue() << e().getValue() % 64;1162case '>':1163return lhs.getValue() >> e().getValue() % 64;1164case '&':1165return lhs.getValue() & e().getValue();1166case '^':1167return lhs.getValue() ^ e().getValue();1168case '|':1169return lhs.getValue() | e().getValue();1170default:1171llvm_unreachable("");1172}1173};1174}1175return make<SymbolAssignment>(name, e, ctx.scriptSymOrderCounter++,1176getCurrentLocation());1177}11781179// This is an operator-precedence parser to parse a linker1180// script expression.1181Expr ScriptParser::readExpr() {1182// Our lexer is context-aware. Set the in-expression bit so that1183// they apply different tokenization rules.1184SaveAndRestore saved(inExpr, true);1185Expr e = readExpr1(readPrimary(), 0);1186return e;1187}11881189Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {1190if (op == "+")1191return [=] { return add(l(), r()); };1192if (op == "-")1193return [=] { return sub(l(), r()); };1194if (op == "*")1195return [=] { return l().getValue() * r().getValue(); };1196if (op == "/") {1197std::string loc = getCurrentLocation();1198return [=]() -> uint64_t {1199if (uint64_t rv = r().getValue())1200return l().getValue() / rv;1201error(loc + ": division by zero");1202return 0;1203};1204}1205if (op == "%") {1206std::string loc = getCurrentLocation();1207return [=]() -> uint64_t {1208if (uint64_t rv = r().getValue())1209return l().getValue() % rv;1210error(loc + ": modulo by zero");1211return 0;1212};1213}1214if (op == "<<")1215return [=] { return l().getValue() << r().getValue() % 64; };1216if (op == ">>")1217return [=] { return l().getValue() >> r().getValue() % 64; };1218if (op == "<")1219return [=] { return l().getValue() < r().getValue(); };1220if (op == ">")1221return [=] { return l().getValue() > r().getValue(); };1222if (op == ">=")1223return [=] { return l().getValue() >= r().getValue(); };1224if (op == "<=")1225return [=] { return l().getValue() <= r().getValue(); };1226if (op == "==")1227return [=] { return l().getValue() == r().getValue(); };1228if (op == "!=")1229return [=] { return l().getValue() != r().getValue(); };1230if (op == "||")1231return [=] { return l().getValue() || r().getValue(); };1232if (op == "&&")1233return [=] { return l().getValue() && r().getValue(); };1234if (op == "&")1235return [=] { return bitAnd(l(), r()); };1236if (op == "^")1237return [=] { return bitXor(l(), r()); };1238if (op == "|")1239return [=] { return bitOr(l(), r()); };1240llvm_unreachable("invalid operator");1241}12421243// This is a part of the operator-precedence parser. This function1244// assumes that the remaining token stream starts with an operator.1245Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {1246while (!atEOF() && !errorCount()) {1247// Read an operator and an expression.1248StringRef op1 = peek();1249if (precedence(op1) < minPrec)1250break;1251skip();1252if (op1 == "?")1253return readTernary(lhs);1254Expr rhs = readPrimary();12551256// Evaluate the remaining part of the expression first if the1257// next operator has greater precedence than the previous one.1258// For example, if we have read "+" and "3", and if the next1259// operator is "*", then we'll evaluate 3 * ... part first.1260while (!atEOF()) {1261StringRef op2 = peek();1262if (precedence(op2) <= precedence(op1))1263break;1264rhs = readExpr1(rhs, precedence(op2));1265}12661267lhs = combine(op1, lhs, rhs);1268}1269return lhs;1270}12711272Expr ScriptParser::getPageSize() {1273std::string location = getCurrentLocation();1274return [=]() -> uint64_t {1275if (target)1276return config->commonPageSize;1277error(location + ": unable to calculate page size");1278return 4096; // Return a dummy value.1279};1280}12811282Expr ScriptParser::readConstant() {1283StringRef s = readParenLiteral();1284if (s == "COMMONPAGESIZE")1285return getPageSize();1286if (s == "MAXPAGESIZE")1287return [] { return config->maxPageSize; };1288setError("unknown constant: " + s);1289return [] { return 0; };1290}12911292// Parses Tok as an integer. It recognizes hexadecimal (prefixed with1293// "0x" or suffixed with "H") and decimal numbers. Decimal numbers may1294// have "K" (Ki) or "M" (Mi) suffixes.1295static std::optional<uint64_t> parseInt(StringRef tok) {1296// Hexadecimal1297uint64_t val;1298if (tok.starts_with_insensitive("0x")) {1299if (!to_integer(tok.substr(2), val, 16))1300return std::nullopt;1301return val;1302}1303if (tok.ends_with_insensitive("H")) {1304if (!to_integer(tok.drop_back(), val, 16))1305return std::nullopt;1306return val;1307}13081309// Decimal1310if (tok.ends_with_insensitive("K")) {1311if (!to_integer(tok.drop_back(), val, 10))1312return std::nullopt;1313return val * 1024;1314}1315if (tok.ends_with_insensitive("M")) {1316if (!to_integer(tok.drop_back(), val, 10))1317return std::nullopt;1318return val * 1024 * 1024;1319}1320if (!to_integer(tok, val, 10))1321return std::nullopt;1322return val;1323}13241325ByteCommand *ScriptParser::readByteCommand(StringRef tok) {1326int size = StringSwitch<int>(tok)1327.Case("BYTE", 1)1328.Case("SHORT", 2)1329.Case("LONG", 4)1330.Case("QUAD", 8)1331.Default(-1);1332if (size == -1)1333return nullptr;13341335size_t oldPos = pos;1336Expr e = readParenExpr();1337std::string commandString =1338tok.str() + " " +1339llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");1340return make<ByteCommand>(e, size, commandString);1341}13421343static std::optional<uint64_t> parseFlag(StringRef tok) {1344if (std::optional<uint64_t> asInt = parseInt(tok))1345return asInt;1346#define CASE_ENT(enum) #enum, ELF::enum1347return StringSwitch<std::optional<uint64_t>>(tok)1348.Case(CASE_ENT(SHF_WRITE))1349.Case(CASE_ENT(SHF_ALLOC))1350.Case(CASE_ENT(SHF_EXECINSTR))1351.Case(CASE_ENT(SHF_MERGE))1352.Case(CASE_ENT(SHF_STRINGS))1353.Case(CASE_ENT(SHF_INFO_LINK))1354.Case(CASE_ENT(SHF_LINK_ORDER))1355.Case(CASE_ENT(SHF_OS_NONCONFORMING))1356.Case(CASE_ENT(SHF_GROUP))1357.Case(CASE_ENT(SHF_TLS))1358.Case(CASE_ENT(SHF_COMPRESSED))1359.Case(CASE_ENT(SHF_EXCLUDE))1360.Case(CASE_ENT(SHF_ARM_PURECODE))1361.Default(std::nullopt);1362#undef CASE_ENT1363}13641365// Reads the '(' <flags> ')' list of section flags in1366// INPUT_SECTION_FLAGS '(' <flags> ')' in the1367// following form:1368// <flags> ::= <flag>1369// | <flags> & flag1370// <flag> ::= Recognized Flag Name, or Integer value of flag.1371// If the first character of <flag> is a ! then this means without flag,1372// otherwise with flag.1373// Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and1374// without flag SHF_WRITE.1375std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {1376uint64_t withFlags = 0;1377uint64_t withoutFlags = 0;1378expect("(");1379while (!errorCount()) {1380StringRef tok = unquote(next());1381bool without = tok.consume_front("!");1382if (std::optional<uint64_t> flag = parseFlag(tok)) {1383if (without)1384withoutFlags |= *flag;1385else1386withFlags |= *flag;1387} else {1388setError("unrecognised flag: " + tok);1389}1390if (consume(")"))1391break;1392if (!consume("&")) {1393next();1394setError("expected & or )");1395}1396}1397return std::make_pair(withFlags, withoutFlags);1398}13991400StringRef ScriptParser::readParenLiteral() {1401expect("(");1402bool orig = inExpr;1403inExpr = false;1404StringRef tok = next();1405inExpr = orig;1406expect(")");1407return tok;1408}14091410static void checkIfExists(const OutputSection &osec, StringRef location) {1411if (osec.location.empty() && script->errorOnMissingSection)1412script->recordError(location + ": undefined section " + osec.name);1413}14141415static bool isValidSymbolName(StringRef s) {1416auto valid = [](char c) {1417return isAlnum(c) || c == '$' || c == '.' || c == '_';1418};1419return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);1420}14211422Expr ScriptParser::readPrimary() {1423if (peek() == "(")1424return readParenExpr();14251426if (consume("~")) {1427Expr e = readPrimary();1428return [=] { return ~e().getValue(); };1429}1430if (consume("!")) {1431Expr e = readPrimary();1432return [=] { return !e().getValue(); };1433}1434if (consume("-")) {1435Expr e = readPrimary();1436return [=] { return -e().getValue(); };1437}14381439StringRef tok = next();1440std::string location = getCurrentLocation();14411442// Built-in functions are parsed here.1443// https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.1444if (tok == "ABSOLUTE") {1445Expr inner = readParenExpr();1446return [=] {1447ExprValue i = inner();1448i.forceAbsolute = true;1449return i;1450};1451}1452if (tok == "ADDR") {1453StringRef name = unquote(readParenLiteral());1454OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;1455osec->usedInExpression = true;1456return [=]() -> ExprValue {1457checkIfExists(*osec, location);1458return {osec, false, 0, location};1459};1460}1461if (tok == "ALIGN") {1462expect("(");1463Expr e = readExpr();1464if (consume(")")) {1465e = checkAlignment(e, location);1466return [=] { return alignToPowerOf2(script->getDot(), e().getValue()); };1467}1468expect(",");1469Expr e2 = checkAlignment(readExpr(), location);1470expect(")");1471return [=] {1472ExprValue v = e();1473v.alignment = e2().getValue();1474return v;1475};1476}1477if (tok == "ALIGNOF") {1478StringRef name = unquote(readParenLiteral());1479OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;1480return [=] {1481checkIfExists(*osec, location);1482return osec->addralign;1483};1484}1485if (tok == "ASSERT")1486return readAssert();1487if (tok == "CONSTANT")1488return readConstant();1489if (tok == "DATA_SEGMENT_ALIGN") {1490expect("(");1491Expr e = readExpr();1492expect(",");1493readExpr();1494expect(")");1495script->seenDataAlign = true;1496return [=] {1497uint64_t align = std::max(uint64_t(1), e().getValue());1498return (script->getDot() + align - 1) & -align;1499};1500}1501if (tok == "DATA_SEGMENT_END") {1502expect("(");1503expect(".");1504expect(")");1505return [] { return script->getDot(); };1506}1507if (tok == "DATA_SEGMENT_RELRO_END") {1508// GNU linkers implements more complicated logic to handle1509// DATA_SEGMENT_RELRO_END. We instead ignore the arguments and1510// just align to the next page boundary for simplicity.1511expect("(");1512readExpr();1513expect(",");1514readExpr();1515expect(")");1516script->seenRelroEnd = true;1517return [=] { return alignToPowerOf2(script->getDot(), config->maxPageSize); };1518}1519if (tok == "DEFINED") {1520StringRef name = unquote(readParenLiteral());1521// Return 1 if s is defined. If the definition is only found in a linker1522// script, it must happen before this DEFINED.1523auto order = ctx.scriptSymOrderCounter++;1524return [=] {1525Symbol *s = symtab.find(name);1526return s && s->isDefined() && ctx.scriptSymOrder.lookup(s) < order ? 11527: 0;1528};1529}1530if (tok == "LENGTH") {1531StringRef name = readParenLiteral();1532if (script->memoryRegions.count(name) == 0) {1533setError("memory region not defined: " + name);1534return [] { return 0; };1535}1536return script->memoryRegions[name]->length;1537}1538if (tok == "LOADADDR") {1539StringRef name = unquote(readParenLiteral());1540OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;1541osec->usedInExpression = true;1542return [=] {1543checkIfExists(*osec, location);1544return osec->getLMA();1545};1546}1547if (tok == "LOG2CEIL") {1548expect("(");1549Expr a = readExpr();1550expect(")");1551return [=] {1552// LOG2CEIL(0) is defined to be 0.1553return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));1554};1555}1556if (tok == "MAX" || tok == "MIN") {1557expect("(");1558Expr a = readExpr();1559expect(",");1560Expr b = readExpr();1561expect(")");1562if (tok == "MIN")1563return [=] { return std::min(a().getValue(), b().getValue()); };1564return [=] { return std::max(a().getValue(), b().getValue()); };1565}1566if (tok == "ORIGIN") {1567StringRef name = readParenLiteral();1568if (script->memoryRegions.count(name) == 0) {1569setError("memory region not defined: " + name);1570return [] { return 0; };1571}1572return script->memoryRegions[name]->origin;1573}1574if (tok == "SEGMENT_START") {1575expect("(");1576skip();1577expect(",");1578Expr e = readExpr();1579expect(")");1580return [=] { return e(); };1581}1582if (tok == "SIZEOF") {1583StringRef name = unquote(readParenLiteral());1584OutputSection *cmd = &script->getOrCreateOutputSection(name)->osec;1585// Linker script does not create an output section if its content is empty.1586// We want to allow SIZEOF(.foo) where .foo is a section which happened to1587// be empty.1588return [=] { return cmd->size; };1589}1590if (tok == "SIZEOF_HEADERS")1591return [=] { return elf::getHeaderSize(); };15921593// Tok is the dot.1594if (tok == ".")1595return [=] { return script->getSymbolValue(tok, location); };15961597// Tok is a literal number.1598if (std::optional<uint64_t> val = parseInt(tok))1599return [=] { return *val; };16001601// Tok is a symbol name.1602if (tok.starts_with("\""))1603tok = unquote(tok);1604else if (!isValidSymbolName(tok))1605setError("malformed number: " + tok);1606if (activeProvideSym)1607script->provideMap[*activeProvideSym].push_back(tok);1608else1609script->referencedSymbols.push_back(tok);1610return [=] { return script->getSymbolValue(tok, location); };1611}16121613Expr ScriptParser::readTernary(Expr cond) {1614Expr l = readExpr();1615expect(":");1616Expr r = readExpr();1617return [=] { return cond().getValue() ? l() : r(); };1618}16191620Expr ScriptParser::readParenExpr() {1621expect("(");1622Expr e = readExpr();1623expect(")");1624return e;1625}16261627SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {1628SmallVector<StringRef, 0> phdrs;1629while (!errorCount() && peek().starts_with(":")) {1630StringRef tok = next();1631phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));1632}1633return phdrs;1634}16351636// Read a program header type name. The next token must be a1637// name of a program header type or a constant (e.g. "0x3").1638unsigned ScriptParser::readPhdrType() {1639StringRef tok = next();1640if (std::optional<uint64_t> val = parseInt(tok))1641return *val;16421643unsigned ret = StringSwitch<unsigned>(tok)1644.Case("PT_NULL", PT_NULL)1645.Case("PT_LOAD", PT_LOAD)1646.Case("PT_DYNAMIC", PT_DYNAMIC)1647.Case("PT_INTERP", PT_INTERP)1648.Case("PT_NOTE", PT_NOTE)1649.Case("PT_SHLIB", PT_SHLIB)1650.Case("PT_PHDR", PT_PHDR)1651.Case("PT_TLS", PT_TLS)1652.Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)1653.Case("PT_GNU_STACK", PT_GNU_STACK)1654.Case("PT_GNU_RELRO", PT_GNU_RELRO)1655.Case("PT_OPENBSD_MUTABLE", PT_OPENBSD_MUTABLE)1656.Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)1657.Case("PT_OPENBSD_SYSCALLS", PT_OPENBSD_SYSCALLS)1658.Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)1659.Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)1660.Default(-1);16611662if (ret == (unsigned)-1) {1663setError("invalid program header type: " + tok);1664return PT_NULL;1665}1666return ret;1667}16681669// Reads an anonymous version declaration.1670void ScriptParser::readAnonymousDeclaration() {1671SmallVector<SymbolVersion, 0> locals;1672SmallVector<SymbolVersion, 0> globals;1673std::tie(locals, globals) = readSymbols();1674for (const SymbolVersion &pat : locals)1675config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat);1676for (const SymbolVersion &pat : globals)1677config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat);16781679expect(";");1680}16811682// Reads a non-anonymous version definition,1683// e.g. "VerStr { global: foo; bar; local: *; };".1684void ScriptParser::readVersionDeclaration(StringRef verStr) {1685// Read a symbol list.1686SmallVector<SymbolVersion, 0> locals;1687SmallVector<SymbolVersion, 0> globals;1688std::tie(locals, globals) = readSymbols();16891690// Create a new version definition and add that to the global symbols.1691VersionDefinition ver;1692ver.name = verStr;1693ver.nonLocalPatterns = std::move(globals);1694ver.localPatterns = std::move(locals);1695ver.id = config->versionDefinitions.size();1696config->versionDefinitions.push_back(ver);16971698// Each version may have a parent version. For example, "Ver2"1699// defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"1700// as a parent. This version hierarchy is, probably against your1701// instinct, purely for hint; the runtime doesn't care about it1702// at all. In LLD, we simply ignore it.1703if (next() != ";")1704expect(";");1705}17061707bool elf::hasWildcard(StringRef s) {1708return s.find_first_of("?*[") != StringRef::npos;1709}17101711// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".1712std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>1713ScriptParser::readSymbols() {1714SmallVector<SymbolVersion, 0> locals;1715SmallVector<SymbolVersion, 0> globals;1716SmallVector<SymbolVersion, 0> *v = &globals;17171718while (!errorCount()) {1719if (consume("}"))1720break;1721if (consumeLabel("local")) {1722v = &locals;1723continue;1724}1725if (consumeLabel("global")) {1726v = &globals;1727continue;1728}17291730if (consume("extern")) {1731SmallVector<SymbolVersion, 0> ext = readVersionExtern();1732v->insert(v->end(), ext.begin(), ext.end());1733} else {1734StringRef tok = next();1735v->push_back({unquote(tok), false, hasWildcard(tok)});1736}1737expect(";");1738}1739return {locals, globals};1740}17411742// Reads an "extern C++" directive, e.g.,1743// "extern "C++" { ns::*; "f(int, double)"; };"1744//1745// The last semicolon is optional. E.g. this is OK:1746// "extern "C++" { ns::*; "f(int, double)" };"1747SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {1748StringRef tok = next();1749bool isCXX = tok == "\"C++\"";1750if (!isCXX && tok != "\"C\"")1751setError("Unknown language");1752expect("{");17531754SmallVector<SymbolVersion, 0> ret;1755while (!errorCount() && peek() != "}") {1756StringRef tok = next();1757ret.push_back(1758{unquote(tok), isCXX, !tok.starts_with("\"") && hasWildcard(tok)});1759if (consume("}"))1760return ret;1761expect(";");1762}17631764expect("}");1765return ret;1766}17671768Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,1769StringRef s3) {1770if (!consume(s1) && !consume(s2) && !consume(s3)) {1771setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);1772return [] { return 0; };1773}1774expect("=");1775return readExpr();1776}17771778// Parse the MEMORY command as specified in:1779// https://sourceware.org/binutils/docs/ld/MEMORY.html1780//1781// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }1782void ScriptParser::readMemory() {1783expect("{");1784while (!errorCount() && !consume("}")) {1785StringRef tok = next();1786if (tok == "INCLUDE") {1787readInclude();1788continue;1789}17901791uint32_t flags = 0;1792uint32_t invFlags = 0;1793uint32_t negFlags = 0;1794uint32_t negInvFlags = 0;1795if (consume("(")) {1796readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);1797expect(")");1798}1799expect(":");18001801Expr origin = readMemoryAssignment("ORIGIN", "org", "o");1802expect(",");1803Expr length = readMemoryAssignment("LENGTH", "len", "l");18041805// Add the memory region to the region map.1806MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags,1807negFlags, negInvFlags);1808if (!script->memoryRegions.insert({tok, mr}).second)1809setError("region '" + tok + "' already defined");1810}1811}18121813// This function parses the attributes used to match against section1814// flags when placing output sections in a memory region. These flags1815// are only used when an explicit memory region name is not used.1816void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,1817uint32_t &negFlags,1818uint32_t &negInvFlags) {1819bool invert = false;18201821for (char c : next().lower()) {1822if (c == '!') {1823invert = !invert;1824std::swap(flags, negFlags);1825std::swap(invFlags, negInvFlags);1826continue;1827}1828if (c == 'w')1829flags |= SHF_WRITE;1830else if (c == 'x')1831flags |= SHF_EXECINSTR;1832else if (c == 'a')1833flags |= SHF_ALLOC;1834else if (c == 'r')1835invFlags |= SHF_WRITE;1836else1837setError("invalid memory region attribute");1838}18391840if (invert) {1841std::swap(flags, negFlags);1842std::swap(invFlags, negInvFlags);1843}1844}18451846void elf::readLinkerScript(MemoryBufferRef mb) {1847llvm::TimeTraceScope timeScope("Read linker script",1848mb.getBufferIdentifier());1849ScriptParser(mb).readLinkerScript();1850}18511852void elf::readVersionScript(MemoryBufferRef mb) {1853llvm::TimeTraceScope timeScope("Read version script",1854mb.getBufferIdentifier());1855ScriptParser(mb).readVersionScript();1856}18571858void elf::readDynamicList(MemoryBufferRef mb) {1859llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());1860ScriptParser(mb).readDynamicList();1861}18621863void elf::readDefsym(StringRef name, MemoryBufferRef mb) {1864llvm::TimeTraceScope timeScope("Read defsym input", name);1865ScriptParser(mb).readDefsym(name);1866}186718681869