11c986198SDimitry Andric //===- ScriptParser.cpp ---------------------------------------------------===//
21c986198SDimitry Andric //
3f1e1c239SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f1e1c239SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5f1e1c239SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61c986198SDimitry Andric //
71c986198SDimitry Andric //===----------------------------------------------------------------------===//
81c986198SDimitry Andric //
9d2d3ebb8SDimitry Andric // This file contains a recursive-descendent parser for linker scripts.
10d2d3ebb8SDimitry Andric // Parsed results are stored to Config and Script global objects.
111c986198SDimitry Andric //
121c986198SDimitry Andric //===----------------------------------------------------------------------===//
131c986198SDimitry Andric
141c986198SDimitry Andric #include "ScriptParser.h"
15d2d3ebb8SDimitry Andric #include "Config.h"
16d2d3ebb8SDimitry Andric #include "Driver.h"
17145449b1SDimitry Andric #include "InputFiles.h"
18d2d3ebb8SDimitry Andric #include "LinkerScript.h"
19d2d3ebb8SDimitry Andric #include "OutputSections.h"
20d2d3ebb8SDimitry Andric #include "ScriptLexer.h"
21145449b1SDimitry Andric #include "SymbolTable.h"
22d2d3ebb8SDimitry Andric #include "Symbols.h"
23d2d3ebb8SDimitry Andric #include "Target.h"
246f8fc217SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
25d2d3ebb8SDimitry Andric #include "llvm/ADT/SmallString.h"
26d2d3ebb8SDimitry Andric #include "llvm/ADT/StringRef.h"
27eb1ff93dSDimitry Andric #include "llvm/ADT/StringSet.h"
28d2d3ebb8SDimitry Andric #include "llvm/ADT/StringSwitch.h"
292079716dSDimitry Andric #include "llvm/BinaryFormat/ELF.h"
30d2d3ebb8SDimitry Andric #include "llvm/Support/Casting.h"
31d2d3ebb8SDimitry Andric #include "llvm/Support/ErrorHandling.h"
32d2d3ebb8SDimitry Andric #include "llvm/Support/FileSystem.h"
33b60736ecSDimitry Andric #include "llvm/Support/MathExtras.h"
34d2d3ebb8SDimitry Andric #include "llvm/Support/Path.h"
35145449b1SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
36b60736ecSDimitry Andric #include "llvm/Support/TimeProfiler.h"
37d2d3ebb8SDimitry Andric #include <cassert>
38d2d3ebb8SDimitry Andric #include <limits>
39ac9a064cSDimitry Andric #include <optional>
40d2d3ebb8SDimitry Andric #include <vector>
411c986198SDimitry Andric
421c986198SDimitry Andric using namespace llvm;
43d2d3ebb8SDimitry Andric using namespace llvm::ELF;
44d2d3ebb8SDimitry Andric using namespace llvm::support::endian;
45cfca06d7SDimitry Andric using namespace lld;
46cfca06d7SDimitry Andric using namespace lld::elf;
471c986198SDimitry Andric
48d2d3ebb8SDimitry Andric namespace {
49d2d3ebb8SDimitry Andric class ScriptParser final : ScriptLexer {
50d2d3ebb8SDimitry Andric public:
ScriptParser(MemoryBufferRef mb)51f1e1c239SDimitry Andric ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) {
52f1e1c239SDimitry Andric // Initialize IsUnderSysroot
53f1e1c239SDimitry Andric if (config->sysroot == "")
54f1e1c239SDimitry Andric return;
55f1e1c239SDimitry Andric StringRef path = mb.getBufferIdentifier();
56f1e1c239SDimitry Andric for (; !path.empty(); path = sys::path::parent_path(path)) {
57f1e1c239SDimitry Andric if (!sys::fs::equivalent(config->sysroot, path))
58f1e1c239SDimitry Andric continue;
59f1e1c239SDimitry Andric isUnderSysroot = true;
60f1e1c239SDimitry Andric return;
61f1e1c239SDimitry Andric }
62f1e1c239SDimitry Andric }
631c986198SDimitry Andric
64d2d3ebb8SDimitry Andric void readLinkerScript();
65d2d3ebb8SDimitry Andric void readVersionScript();
66d2d3ebb8SDimitry Andric void readDynamicList();
67f1e1c239SDimitry Andric void readDefsym(StringRef name);
681c986198SDimitry Andric
69d2d3ebb8SDimitry Andric private:
70f1e1c239SDimitry Andric void addFile(StringRef path);
71d93e1dfaSDimitry Andric
72d2d3ebb8SDimitry Andric void readAsNeeded();
73d2d3ebb8SDimitry Andric void readEntry();
74d2d3ebb8SDimitry Andric void readExtern();
75d2d3ebb8SDimitry Andric void readGroup();
76d2d3ebb8SDimitry Andric void readInclude();
7720d35e67SDimitry Andric void readInput();
78d2d3ebb8SDimitry Andric void readMemory();
79d2d3ebb8SDimitry Andric void readOutput();
80d2d3ebb8SDimitry Andric void readOutputArch();
81d2d3ebb8SDimitry Andric void readOutputFormat();
82344a3780SDimitry Andric void readOverwriteSections();
83d2d3ebb8SDimitry Andric void readPhdrs();
84eb1ff93dSDimitry Andric void readRegionAlias();
85d2d3ebb8SDimitry Andric void readSearchDir();
86d2d3ebb8SDimitry Andric void readSections();
87e2fd426bSDimitry Andric void readTarget();
88d2d3ebb8SDimitry Andric void readVersion();
89d2d3ebb8SDimitry Andric void readVersionScriptCommand();
90ac9a064cSDimitry Andric void readNoCrossRefs(bool to);
91d93e1dfaSDimitry Andric
92f1e1c239SDimitry Andric SymbolAssignment *readSymbolAssignment(StringRef name);
93f1e1c239SDimitry Andric ByteCommand *readByteCommand(StringRef tok);
94e2fd426bSDimitry Andric std::array<uint8_t, 4> readFill();
95ac9a064cSDimitry Andric bool readSectionDirective(OutputSection *cmd, StringRef tok);
96f1e1c239SDimitry Andric void readSectionAddressType(OutputSection *cmd);
97145449b1SDimitry Andric OutputDesc *readOverlaySectionDescription();
98145449b1SDimitry Andric OutputDesc *readOutputSectionDescription(StringRef outSec);
996f8fc217SDimitry Andric SmallVector<SectionCommand *, 0> readOverlay();
1006f8fc217SDimitry Andric SmallVector<StringRef, 0> readOutputSectionPhdrs();
101cfca06d7SDimitry Andric std::pair<uint64_t, uint64_t> readInputSectionFlags();
102f1e1c239SDimitry Andric InputSectionDescription *readInputSectionDescription(StringRef tok);
103d2d3ebb8SDimitry Andric StringMatcher readFilePatterns();
1046f8fc217SDimitry Andric SmallVector<SectionPattern, 0> readInputSectionsList();
105cfca06d7SDimitry Andric InputSectionDescription *readInputSectionRules(StringRef filePattern,
106cfca06d7SDimitry Andric uint64_t withFlags,
107cfca06d7SDimitry Andric uint64_t withoutFlags);
108d2d3ebb8SDimitry Andric unsigned readPhdrType();
109b60736ecSDimitry Andric SortSectionPolicy peekSortKind();
110d2d3ebb8SDimitry Andric SortSectionPolicy readSortKind();
111f1e1c239SDimitry Andric SymbolAssignment *readProvideHidden(bool provide, bool hidden);
112f1e1c239SDimitry Andric SymbolAssignment *readAssignment(StringRef tok);
113d2d3ebb8SDimitry Andric void readSort();
11420d35e67SDimitry Andric Expr readAssert();
115eb1ff93dSDimitry Andric Expr readConstant();
116eb1ff93dSDimitry Andric Expr getPageSize();
117d93e1dfaSDimitry Andric
118cfca06d7SDimitry Andric Expr readMemoryAssignment(StringRef, StringRef, StringRef);
119f65dcba8SDimitry Andric void readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
120f65dcba8SDimitry Andric uint32_t &negFlags, uint32_t &negInvFlags);
121d93e1dfaSDimitry Andric
122f1e1c239SDimitry Andric Expr combine(StringRef op, Expr l, Expr r);
123d2d3ebb8SDimitry Andric Expr readExpr();
124f1e1c239SDimitry Andric Expr readExpr1(Expr lhs, int minPrec);
125d2d3ebb8SDimitry Andric StringRef readParenLiteral();
126d2d3ebb8SDimitry Andric Expr readPrimary();
127f1e1c239SDimitry Andric Expr readTernary(Expr cond);
128d2d3ebb8SDimitry Andric Expr readParenExpr();
129d93e1dfaSDimitry Andric
130d2d3ebb8SDimitry Andric // For parsing version script.
1316f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> readVersionExtern();
132d2d3ebb8SDimitry Andric void readAnonymousDeclaration();
133f1e1c239SDimitry Andric void readVersionDeclaration(StringRef verStr);
1341c986198SDimitry Andric
1356f8fc217SDimitry Andric std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
136d2d3ebb8SDimitry Andric readSymbols();
137d93e1dfaSDimitry Andric
138c0981da4SDimitry Andric // True if a script being read is in the --sysroot directory.
139f1e1c239SDimitry Andric bool isUnderSysroot = false;
140eb1ff93dSDimitry Andric
141eb1ff93dSDimitry Andric // A set to detect an INCLUDE() cycle.
142f1e1c239SDimitry Andric StringSet<> seen;
143ac9a064cSDimitry Andric
144ac9a064cSDimitry Andric // If we are currently parsing a PROVIDE|PROVIDE_HIDDEN command,
145ac9a064cSDimitry Andric // then this member is set to the PROVIDE symbol name.
146ac9a064cSDimitry Andric std::optional<llvm::StringRef> activeProvideSym;
147d2d3ebb8SDimitry Andric };
148d2d3ebb8SDimitry Andric } // namespace
1491c986198SDimitry Andric
unquote(StringRef s)150f1e1c239SDimitry Andric static StringRef unquote(StringRef s) {
1517fa27ce4SDimitry Andric if (s.starts_with("\""))
152f1e1c239SDimitry Andric return s.substr(1, s.size() - 2);
153f1e1c239SDimitry Andric return s;
154d93e1dfaSDimitry Andric }
155d93e1dfaSDimitry Andric
156d2d3ebb8SDimitry Andric // Some operations only support one non absolute value. Move the
157d2d3ebb8SDimitry Andric // absolute one to the right hand side for convenience.
moveAbsRight(ExprValue & a,ExprValue & b)158f1e1c239SDimitry Andric static void moveAbsRight(ExprValue &a, ExprValue &b) {
159f1e1c239SDimitry Andric if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
160f1e1c239SDimitry Andric std::swap(a, b);
161f1e1c239SDimitry Andric if (!b.isAbsolute())
162ac9a064cSDimitry Andric script->recordError(
163ac9a064cSDimitry Andric a.loc + ": at least one side of the expression must be absolute");
164d2d3ebb8SDimitry Andric }
1651c986198SDimitry Andric
add(ExprValue a,ExprValue b)166f1e1c239SDimitry Andric static ExprValue add(ExprValue a, ExprValue b) {
167f1e1c239SDimitry Andric moveAbsRight(a, b);
168f1e1c239SDimitry Andric return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
169d2d3ebb8SDimitry Andric }
170d2d3ebb8SDimitry Andric
sub(ExprValue a,ExprValue b)171f1e1c239SDimitry Andric static ExprValue sub(ExprValue a, ExprValue b) {
172ae1a339dSDimitry Andric // The distance between two symbols in sections is absolute.
173f1e1c239SDimitry Andric if (!a.isAbsolute() && !b.isAbsolute())
174f1e1c239SDimitry Andric return a.getValue() - b.getValue();
175f1e1c239SDimitry Andric return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
176d2d3ebb8SDimitry Andric }
177d2d3ebb8SDimitry Andric
bitAnd(ExprValue a,ExprValue b)178f1e1c239SDimitry Andric static ExprValue bitAnd(ExprValue a, ExprValue b) {
179f1e1c239SDimitry Andric moveAbsRight(a, b);
180f1e1c239SDimitry Andric return {a.sec, a.forceAbsolute,
181f1e1c239SDimitry Andric (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
182d2d3ebb8SDimitry Andric }
183d2d3ebb8SDimitry Andric
bitXor(ExprValue a,ExprValue b)1847fa27ce4SDimitry Andric static ExprValue bitXor(ExprValue a, ExprValue b) {
1857fa27ce4SDimitry Andric moveAbsRight(a, b);
1867fa27ce4SDimitry Andric return {a.sec, a.forceAbsolute,
1877fa27ce4SDimitry Andric (a.getValue() ^ b.getValue()) - a.getSecAddr(), a.loc};
1887fa27ce4SDimitry Andric }
1897fa27ce4SDimitry Andric
bitOr(ExprValue a,ExprValue b)190f1e1c239SDimitry Andric static ExprValue bitOr(ExprValue a, ExprValue b) {
191f1e1c239SDimitry Andric moveAbsRight(a, b);
192f1e1c239SDimitry Andric return {a.sec, a.forceAbsolute,
193f1e1c239SDimitry Andric (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
194d2d3ebb8SDimitry Andric }
195d2d3ebb8SDimitry Andric
readDynamicList()196d2d3ebb8SDimitry Andric void ScriptParser::readDynamicList() {
197d2d3ebb8SDimitry Andric expect("{");
1986f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> locals;
1996f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> globals;
200f1e1c239SDimitry Andric std::tie(locals, globals) = readSymbols();
201eb1ff93dSDimitry Andric expect(";");
202eb1ff93dSDimitry Andric
203eb1ff93dSDimitry Andric if (!atEOF()) {
204d2d3ebb8SDimitry Andric setError("EOF expected, but got " + next());
205eb1ff93dSDimitry Andric return;
206eb1ff93dSDimitry Andric }
207f1e1c239SDimitry Andric if (!locals.empty()) {
208eb1ff93dSDimitry Andric setError("\"local:\" scope not supported in --dynamic-list");
209eb1ff93dSDimitry Andric return;
210eb1ff93dSDimitry Andric }
211eb1ff93dSDimitry Andric
212f1e1c239SDimitry Andric for (SymbolVersion v : globals)
213f1e1c239SDimitry Andric config->dynamicList.push_back(v);
214d2d3ebb8SDimitry Andric }
215d2d3ebb8SDimitry Andric
readVersionScript()216d2d3ebb8SDimitry Andric void ScriptParser::readVersionScript() {
217d2d3ebb8SDimitry Andric readVersionScriptCommand();
218d2d3ebb8SDimitry Andric if (!atEOF())
219d2d3ebb8SDimitry Andric setError("EOF expected, but got " + next());
220d2d3ebb8SDimitry Andric }
221d2d3ebb8SDimitry Andric
readVersionScriptCommand()222d2d3ebb8SDimitry Andric void ScriptParser::readVersionScriptCommand() {
223d2d3ebb8SDimitry Andric if (consume("{")) {
224d2d3ebb8SDimitry Andric readAnonymousDeclaration();
2251c986198SDimitry Andric return;
226d2d3ebb8SDimitry Andric }
227d2d3ebb8SDimitry Andric
228eb1ff93dSDimitry Andric while (!atEOF() && !errorCount() && peek() != "}") {
229f1e1c239SDimitry Andric StringRef verStr = next();
230f1e1c239SDimitry Andric if (verStr == "{") {
231d2d3ebb8SDimitry Andric setError("anonymous version definition is used in "
232d2d3ebb8SDimitry Andric "combination with other version definitions");
233d2d3ebb8SDimitry Andric return;
234d2d3ebb8SDimitry Andric }
235d2d3ebb8SDimitry Andric expect("{");
236f1e1c239SDimitry Andric readVersionDeclaration(verStr);
237d2d3ebb8SDimitry Andric }
238d2d3ebb8SDimitry Andric }
239d2d3ebb8SDimitry Andric
readVersion()240d2d3ebb8SDimitry Andric void ScriptParser::readVersion() {
241d2d3ebb8SDimitry Andric expect("{");
242d2d3ebb8SDimitry Andric readVersionScriptCommand();
243d2d3ebb8SDimitry Andric expect("}");
244d2d3ebb8SDimitry Andric }
245d2d3ebb8SDimitry Andric
readLinkerScript()246d2d3ebb8SDimitry Andric void ScriptParser::readLinkerScript() {
247d2d3ebb8SDimitry Andric while (!atEOF()) {
248f1e1c239SDimitry Andric StringRef tok = next();
249f1e1c239SDimitry Andric if (tok == ";")
250d2d3ebb8SDimitry Andric continue;
251d2d3ebb8SDimitry Andric
252f1e1c239SDimitry Andric if (tok == "ENTRY") {
253d2d3ebb8SDimitry Andric readEntry();
254f1e1c239SDimitry Andric } else if (tok == "EXTERN") {
255d2d3ebb8SDimitry Andric readExtern();
256f1e1c239SDimitry Andric } else if (tok == "GROUP") {
257d2d3ebb8SDimitry Andric readGroup();
258f1e1c239SDimitry Andric } else if (tok == "INCLUDE") {
259d2d3ebb8SDimitry Andric readInclude();
260f1e1c239SDimitry Andric } else if (tok == "INPUT") {
26120d35e67SDimitry Andric readInput();
262f1e1c239SDimitry Andric } else if (tok == "MEMORY") {
263d2d3ebb8SDimitry Andric readMemory();
264f1e1c239SDimitry Andric } else if (tok == "OUTPUT") {
265d2d3ebb8SDimitry Andric readOutput();
266f1e1c239SDimitry Andric } else if (tok == "OUTPUT_ARCH") {
267d2d3ebb8SDimitry Andric readOutputArch();
268f1e1c239SDimitry Andric } else if (tok == "OUTPUT_FORMAT") {
269d2d3ebb8SDimitry Andric readOutputFormat();
270344a3780SDimitry Andric } else if (tok == "OVERWRITE_SECTIONS") {
271344a3780SDimitry Andric readOverwriteSections();
272f1e1c239SDimitry Andric } else if (tok == "PHDRS") {
273d2d3ebb8SDimitry Andric readPhdrs();
274f1e1c239SDimitry Andric } else if (tok == "REGION_ALIAS") {
275eb1ff93dSDimitry Andric readRegionAlias();
276f1e1c239SDimitry Andric } else if (tok == "SEARCH_DIR") {
277d2d3ebb8SDimitry Andric readSearchDir();
278f1e1c239SDimitry Andric } else if (tok == "SECTIONS") {
279d2d3ebb8SDimitry Andric readSections();
280f1e1c239SDimitry Andric } else if (tok == "TARGET") {
281e2fd426bSDimitry Andric readTarget();
282f1e1c239SDimitry Andric } else if (tok == "VERSION") {
283d2d3ebb8SDimitry Andric readVersion();
284ac9a064cSDimitry Andric } else if (tok == "NOCROSSREFS") {
285ac9a064cSDimitry Andric readNoCrossRefs(/*to=*/false);
286ac9a064cSDimitry Andric } else if (tok == "NOCROSSREFS_TO") {
287ac9a064cSDimitry Andric readNoCrossRefs(/*to=*/true);
288f1e1c239SDimitry Andric } else if (SymbolAssignment *cmd = readAssignment(tok)) {
289f1e1c239SDimitry Andric script->sectionCommands.push_back(cmd);
290d2d3ebb8SDimitry Andric } else {
291f1e1c239SDimitry Andric setError("unknown directive: " + tok);
292d2d3ebb8SDimitry Andric }
293d2d3ebb8SDimitry Andric }
2941c986198SDimitry Andric }
2951c986198SDimitry Andric
readDefsym(StringRef name)296f1e1c239SDimitry Andric void ScriptParser::readDefsym(StringRef name) {
297e2fd426bSDimitry Andric if (errorCount())
298e2fd426bSDimitry Andric return;
299f1e1c239SDimitry Andric Expr e = readExpr();
300eb1ff93dSDimitry Andric if (!atEOF())
301eb1ff93dSDimitry Andric setError("EOF expected, but got " + next());
3024df029ccSDimitry Andric auto *cmd = make<SymbolAssignment>(
3034df029ccSDimitry Andric name, e, 0, getCurrentMB().getBufferIdentifier().str());
304f1e1c239SDimitry Andric script->sectionCommands.push_back(cmd);
305eb1ff93dSDimitry Andric }
306eb1ff93dSDimitry Andric
readNoCrossRefs(bool to)307ac9a064cSDimitry Andric void ScriptParser::readNoCrossRefs(bool to) {
308ac9a064cSDimitry Andric expect("(");
309ac9a064cSDimitry Andric NoCrossRefCommand cmd{{}, to};
310ac9a064cSDimitry Andric while (!errorCount() && !consume(")"))
311ac9a064cSDimitry Andric cmd.outputSections.push_back(unquote(next()));
312ac9a064cSDimitry Andric if (cmd.outputSections.size() < 2)
313ac9a064cSDimitry Andric warn(getCurrentLocation() + ": ignored with fewer than 2 output sections");
314ac9a064cSDimitry Andric else
315ac9a064cSDimitry Andric script->noCrossRefs.push_back(std::move(cmd));
316ac9a064cSDimitry Andric }
317ac9a064cSDimitry Andric
addFile(StringRef s)318f1e1c239SDimitry Andric void ScriptParser::addFile(StringRef s) {
3197fa27ce4SDimitry Andric if (isUnderSysroot && s.starts_with("/")) {
320f1e1c239SDimitry Andric SmallString<128> pathData;
321f1e1c239SDimitry Andric StringRef path = (config->sysroot + s).toStringRef(pathData);
322344a3780SDimitry Andric if (sys::fs::exists(path))
323e3b55780SDimitry Andric ctx.driver.addFile(saver().save(path), /*withLOption=*/false);
324344a3780SDimitry Andric else
325344a3780SDimitry Andric setError("cannot find " + s + " inside " + config->sysroot);
326d2d3ebb8SDimitry Andric return;
327d2d3ebb8SDimitry Andric }
328d93e1dfaSDimitry Andric
3297fa27ce4SDimitry Andric if (s.starts_with("/")) {
330cfca06d7SDimitry Andric // Case 1: s is an absolute path. Just open it.
331e3b55780SDimitry Andric ctx.driver.addFile(s, /*withLOption=*/false);
3327fa27ce4SDimitry Andric } else if (s.starts_with("=")) {
333cfca06d7SDimitry Andric // Case 2: relative to the sysroot.
334f1e1c239SDimitry Andric if (config->sysroot.empty())
335e3b55780SDimitry Andric ctx.driver.addFile(s.substr(1), /*withLOption=*/false);
336d2d3ebb8SDimitry Andric else
337e3b55780SDimitry Andric ctx.driver.addFile(saver().save(config->sysroot + "/" + s.substr(1)),
338f1e1c239SDimitry Andric /*withLOption=*/false);
3397fa27ce4SDimitry Andric } else if (s.starts_with("-l")) {
340cfca06d7SDimitry Andric // Case 3: search in the list of library paths.
341e3b55780SDimitry Andric ctx.driver.addLibrary(s.substr(2));
342cfca06d7SDimitry Andric } else {
343cfca06d7SDimitry Andric // Case 4: s is a relative path. Search in the directory of the script file.
344cfca06d7SDimitry Andric std::string filename = std::string(getCurrentMB().getBufferIdentifier());
345cfca06d7SDimitry Andric StringRef directory = sys::path::parent_path(filename);
346cfca06d7SDimitry Andric if (!directory.empty()) {
347cfca06d7SDimitry Andric SmallString<0> path(directory);
348cfca06d7SDimitry Andric sys::path::append(path, s);
349cfca06d7SDimitry Andric if (sys::fs::exists(path)) {
350e3b55780SDimitry Andric ctx.driver.addFile(path, /*withLOption=*/false);
351cfca06d7SDimitry Andric return;
352cfca06d7SDimitry Andric }
353cfca06d7SDimitry Andric }
354cfca06d7SDimitry Andric // Then search in the current working directory.
355cfca06d7SDimitry Andric if (sys::fs::exists(s)) {
356e3b55780SDimitry Andric ctx.driver.addFile(s, /*withLOption=*/false);
357d2d3ebb8SDimitry Andric } else {
358cfca06d7SDimitry Andric // Finally, search in the list of library paths.
359e3b55780SDimitry Andric if (std::optional<std::string> path = findFromSearchPaths(s))
360e3b55780SDimitry Andric ctx.driver.addFile(saver().save(*path), /*withLOption=*/true);
361d2d3ebb8SDimitry Andric else
362f1e1c239SDimitry Andric setError("unable to find " + s);
363d2d3ebb8SDimitry Andric }
364d2d3ebb8SDimitry Andric }
365cfca06d7SDimitry Andric }
366d93e1dfaSDimitry Andric
readAsNeeded()367d2d3ebb8SDimitry Andric void ScriptParser::readAsNeeded() {
368d2d3ebb8SDimitry Andric expect("(");
369f1e1c239SDimitry Andric bool orig = config->asNeeded;
370f1e1c239SDimitry Andric config->asNeeded = true;
371eb1ff93dSDimitry Andric while (!errorCount() && !consume(")"))
372d2d3ebb8SDimitry Andric addFile(unquote(next()));
373f1e1c239SDimitry Andric config->asNeeded = orig;
374d2d3ebb8SDimitry Andric }
375d2d3ebb8SDimitry Andric
readEntry()376d2d3ebb8SDimitry Andric void ScriptParser::readEntry() {
377d2d3ebb8SDimitry Andric // -e <symbol> takes predecence over ENTRY(<symbol>).
378d2d3ebb8SDimitry Andric expect("(");
379f1e1c239SDimitry Andric StringRef tok = next();
380f1e1c239SDimitry Andric if (config->entry.empty())
381145449b1SDimitry Andric config->entry = unquote(tok);
382d2d3ebb8SDimitry Andric expect(")");
383d2d3ebb8SDimitry Andric }
384d2d3ebb8SDimitry Andric
readExtern()385d2d3ebb8SDimitry Andric void ScriptParser::readExtern() {
386d2d3ebb8SDimitry Andric expect("(");
387eb1ff93dSDimitry Andric while (!errorCount() && !consume(")"))
388f1e1c239SDimitry Andric config->undefined.push_back(unquote(next()));
389d2d3ebb8SDimitry Andric }
390d2d3ebb8SDimitry Andric
readGroup()391d2d3ebb8SDimitry Andric void ScriptParser::readGroup() {
392f1e1c239SDimitry Andric bool orig = InputFile::isInGroup;
393f1e1c239SDimitry Andric InputFile::isInGroup = true;
39420d35e67SDimitry Andric readInput();
395f1e1c239SDimitry Andric InputFile::isInGroup = orig;
396f1e1c239SDimitry Andric if (!orig)
397f1e1c239SDimitry Andric ++InputFile::nextGroupId;
398d2d3ebb8SDimitry Andric }
399d2d3ebb8SDimitry Andric
readInclude()400d2d3ebb8SDimitry Andric void ScriptParser::readInclude() {
401f1e1c239SDimitry Andric StringRef tok = unquote(next());
402d2d3ebb8SDimitry Andric
403f1e1c239SDimitry Andric if (!seen.insert(tok).second) {
404eb1ff93dSDimitry Andric setError("there is a cycle in linker script INCLUDEs");
405d2d3ebb8SDimitry Andric return;
406d2d3ebb8SDimitry Andric }
407eb1ff93dSDimitry Andric
408e3b55780SDimitry Andric if (std::optional<std::string> path = searchScript(tok)) {
409e3b55780SDimitry Andric if (std::optional<MemoryBufferRef> mb = readFile(*path))
410f1e1c239SDimitry Andric tokenize(*mb);
411d2d3ebb8SDimitry Andric return;
412d2d3ebb8SDimitry Andric }
413f1e1c239SDimitry Andric setError("cannot find linker script " + tok);
414d2d3ebb8SDimitry Andric }
415d2d3ebb8SDimitry Andric
readInput()41620d35e67SDimitry Andric void ScriptParser::readInput() {
41720d35e67SDimitry Andric expect("(");
41820d35e67SDimitry Andric while (!errorCount() && !consume(")")) {
41920d35e67SDimitry Andric if (consume("AS_NEEDED"))
42020d35e67SDimitry Andric readAsNeeded();
42120d35e67SDimitry Andric else
42220d35e67SDimitry Andric addFile(unquote(next()));
42320d35e67SDimitry Andric }
42420d35e67SDimitry Andric }
42520d35e67SDimitry Andric
readOutput()426d2d3ebb8SDimitry Andric void ScriptParser::readOutput() {
427d2d3ebb8SDimitry Andric // -o <file> takes predecence over OUTPUT(<file>).
428d2d3ebb8SDimitry Andric expect("(");
429f1e1c239SDimitry Andric StringRef tok = next();
430f1e1c239SDimitry Andric if (config->outputFile.empty())
431f1e1c239SDimitry Andric config->outputFile = unquote(tok);
432d2d3ebb8SDimitry Andric expect(")");
433d2d3ebb8SDimitry Andric }
434d2d3ebb8SDimitry Andric
readOutputArch()435d2d3ebb8SDimitry Andric void ScriptParser::readOutputArch() {
436d2d3ebb8SDimitry Andric // OUTPUT_ARCH is ignored for now.
437d2d3ebb8SDimitry Andric expect("(");
438eb1ff93dSDimitry Andric while (!errorCount() && !consume(")"))
439d2d3ebb8SDimitry Andric skip();
440d2d3ebb8SDimitry Andric }
441d2d3ebb8SDimitry Andric
parseBfdName(StringRef s)442f1e1c239SDimitry Andric static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
443f1e1c239SDimitry Andric return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
444f1e1c239SDimitry Andric .Case("elf32-i386", {ELF32LEKind, EM_386})
445145449b1SDimitry Andric .Case("elf32-avr", {ELF32LEKind, EM_AVR})
446f1e1c239SDimitry Andric .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
447f1e1c239SDimitry Andric .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
4487fa27ce4SDimitry Andric .Case("elf32-bigarm", {ELF32BEKind, EM_ARM})
449f1e1c239SDimitry Andric .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
450f1e1c239SDimitry Andric .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
451f1e1c239SDimitry Andric .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
452344a3780SDimitry Andric .Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64})
453f1e1c239SDimitry Andric .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
454b60736ecSDimitry Andric .Case("elf32-powerpcle", {ELF32LEKind, EM_PPC})
455f1e1c239SDimitry Andric .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
456f1e1c239SDimitry Andric .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
457f1e1c239SDimitry Andric .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
458f1e1c239SDimitry Andric .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
459f1e1c239SDimitry Andric .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
460f1e1c239SDimitry Andric .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
461f1e1c239SDimitry Andric .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
462f1e1c239SDimitry Andric .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
463f1e1c239SDimitry Andric .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
464f1e1c239SDimitry Andric .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})
465f1e1c239SDimitry Andric .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})
466cfca06d7SDimitry Andric .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9})
467b60736ecSDimitry Andric .Case("elf32-msp430", {ELF32LEKind, EM_MSP430})
4687fa27ce4SDimitry Andric .Case("elf32-loongarch", {ELF32LEKind, EM_LOONGARCH})
4697fa27ce4SDimitry Andric .Case("elf64-loongarch", {ELF64LEKind, EM_LOONGARCH})
470ac9a064cSDimitry Andric .Case("elf64-s390", {ELF64BEKind, EM_S390})
471ac9a064cSDimitry Andric .Cases("elf32-hexagon", "elf32-littlehexagon", {ELF32LEKind, EM_HEXAGON})
472f1e1c239SDimitry Andric .Default({ELFNoneKind, EM_NONE});
473e2fd426bSDimitry Andric }
474e2fd426bSDimitry Andric
475344a3780SDimitry Andric // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
476344a3780SDimitry Andric // big if -EB is specified, little if -EL is specified, or default if neither is
477344a3780SDimitry Andric // specified.
readOutputFormat()478d2d3ebb8SDimitry Andric void ScriptParser::readOutputFormat() {
479d2d3ebb8SDimitry Andric expect("(");
480e2fd426bSDimitry Andric
481ac9a064cSDimitry Andric StringRef s = unquote(next());
482344a3780SDimitry Andric if (!consume(")")) {
483344a3780SDimitry Andric expect(",");
484ac9a064cSDimitry Andric StringRef tmp = unquote(next());
485344a3780SDimitry Andric if (config->optEB)
486ac9a064cSDimitry Andric s = tmp;
487344a3780SDimitry Andric expect(",");
488ac9a064cSDimitry Andric tmp = unquote(next());
489344a3780SDimitry Andric if (config->optEL)
490ac9a064cSDimitry Andric s = tmp;
491344a3780SDimitry Andric consume(")");
492344a3780SDimitry Andric }
493ac9a064cSDimitry Andric // If more than one OUTPUT_FORMAT is specified, only the first is checked.
494ac9a064cSDimitry Andric if (!config->bfdname.empty())
495ac9a064cSDimitry Andric return;
496ac9a064cSDimitry Andric config->bfdname = s;
497ac9a064cSDimitry Andric
498ac9a064cSDimitry Andric if (s == "binary") {
499ac9a064cSDimitry Andric config->oFormatBinary = true;
500ac9a064cSDimitry Andric return;
501ac9a064cSDimitry Andric }
502ac9a064cSDimitry Andric
503f1e1c239SDimitry Andric if (s.consume_back("-freebsd"))
504f1e1c239SDimitry Andric config->osabi = ELFOSABI_FREEBSD;
505f1e1c239SDimitry Andric
506f1e1c239SDimitry Andric std::tie(config->ekind, config->emachine) = parseBfdName(s);
507f1e1c239SDimitry Andric if (config->emachine == EM_NONE)
508cfca06d7SDimitry Andric setError("unknown output format name: " + config->bfdname);
509f1e1c239SDimitry Andric if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
510f1e1c239SDimitry Andric config->mipsN32Abi = true;
511b60736ecSDimitry Andric if (config->emachine == EM_MSP430)
512b60736ecSDimitry Andric config->osabi = ELFOSABI_STANDALONE;
513d2d3ebb8SDimitry Andric }
514d2d3ebb8SDimitry Andric
readPhdrs()515d2d3ebb8SDimitry Andric void ScriptParser::readPhdrs() {
516d2d3ebb8SDimitry Andric expect("{");
517d2d3ebb8SDimitry Andric
518eb1ff93dSDimitry Andric while (!errorCount() && !consume("}")) {
519f1e1c239SDimitry Andric PhdrsCommand cmd;
520f1e1c239SDimitry Andric cmd.name = next();
521f1e1c239SDimitry Andric cmd.type = readPhdrType();
522d2d3ebb8SDimitry Andric
523eb1ff93dSDimitry Andric while (!errorCount() && !consume(";")) {
524d2d3ebb8SDimitry Andric if (consume("FILEHDR"))
525f1e1c239SDimitry Andric cmd.hasFilehdr = true;
526d2d3ebb8SDimitry Andric else if (consume("PHDRS"))
527f1e1c239SDimitry Andric cmd.hasPhdrs = true;
528d2d3ebb8SDimitry Andric else if (consume("AT"))
529f1e1c239SDimitry Andric cmd.lmaExpr = readParenExpr();
530d2d3ebb8SDimitry Andric else if (consume("FLAGS"))
531f1e1c239SDimitry Andric cmd.flags = readParenExpr()().getValue();
532d2d3ebb8SDimitry Andric else
533d2d3ebb8SDimitry Andric setError("unexpected header attribute: " + next());
534d2d3ebb8SDimitry Andric }
535eb1ff93dSDimitry Andric
536f1e1c239SDimitry Andric script->phdrsCommands.push_back(cmd);
537d2d3ebb8SDimitry Andric }
538d2d3ebb8SDimitry Andric }
539d2d3ebb8SDimitry Andric
readRegionAlias()540eb1ff93dSDimitry Andric void ScriptParser::readRegionAlias() {
541eb1ff93dSDimitry Andric expect("(");
542f1e1c239SDimitry Andric StringRef alias = unquote(next());
543eb1ff93dSDimitry Andric expect(",");
544f1e1c239SDimitry Andric StringRef name = next();
545eb1ff93dSDimitry Andric expect(")");
546eb1ff93dSDimitry Andric
547f1e1c239SDimitry Andric if (script->memoryRegions.count(alias))
548f1e1c239SDimitry Andric setError("redefinition of memory region '" + alias + "'");
549f1e1c239SDimitry Andric if (!script->memoryRegions.count(name))
550f1e1c239SDimitry Andric setError("memory region '" + name + "' is not defined");
551f1e1c239SDimitry Andric script->memoryRegions.insert({alias, script->memoryRegions[name]});
552eb1ff93dSDimitry Andric }
553eb1ff93dSDimitry Andric
readSearchDir()554d2d3ebb8SDimitry Andric void ScriptParser::readSearchDir() {
555d2d3ebb8SDimitry Andric expect("(");
556f1e1c239SDimitry Andric StringRef tok = next();
557f1e1c239SDimitry Andric if (!config->nostdlib)
558f1e1c239SDimitry Andric config->searchPaths.push_back(unquote(tok));
559d2d3ebb8SDimitry Andric expect(")");
560d2d3ebb8SDimitry Andric }
561d2d3ebb8SDimitry Andric
56220d35e67SDimitry Andric // This reads an overlay description. Overlays are used to describe output
56320d35e67SDimitry Andric // sections that use the same virtual memory range and normally would trigger
56420d35e67SDimitry Andric // linker's sections sanity check failures.
56520d35e67SDimitry Andric // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
readOverlay()5666f8fc217SDimitry Andric SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() {
567aca2e42cSDimitry Andric Expr addrExpr;
568aca2e42cSDimitry Andric if (consume(":")) {
569aca2e42cSDimitry Andric addrExpr = [] { return script->getDot(); };
570aca2e42cSDimitry Andric } else {
571aca2e42cSDimitry Andric addrExpr = readExpr();
57220d35e67SDimitry Andric expect(":");
573aca2e42cSDimitry Andric }
574aca2e42cSDimitry Andric // When AT is omitted, LMA should equal VMA. script->getDot() when evaluating
575aca2e42cSDimitry Andric // lmaExpr will ensure this, even if the start address is specified.
576aca2e42cSDimitry Andric Expr lmaExpr =
577aca2e42cSDimitry Andric consume("AT") ? readParenExpr() : [] { return script->getDot(); };
57820d35e67SDimitry Andric expect("{");
57920d35e67SDimitry Andric
5806f8fc217SDimitry Andric SmallVector<SectionCommand *, 0> v;
581f1e1c239SDimitry Andric OutputSection *prev = nullptr;
58220d35e67SDimitry Andric while (!errorCount() && !consume("}")) {
58320d35e67SDimitry Andric // VA is the same for all sections. The LMAs are consecutive in memory
58420d35e67SDimitry Andric // starting from the base load address specified.
585145449b1SDimitry Andric OutputDesc *osd = readOverlaySectionDescription();
586145449b1SDimitry Andric osd->osec.addrExpr = addrExpr;
587aca2e42cSDimitry Andric if (prev) {
588145449b1SDimitry Andric osd->osec.lmaExpr = [=] { return prev->getLMA() + prev->size; };
589aca2e42cSDimitry Andric } else {
590145449b1SDimitry Andric osd->osec.lmaExpr = lmaExpr;
591aca2e42cSDimitry Andric // Use first section address for subsequent sections as initial addrExpr
592aca2e42cSDimitry Andric // can be DOT. Ensure the first section, even if empty, is not discarded.
593aca2e42cSDimitry Andric osd->osec.usedInExpression = true;
594aca2e42cSDimitry Andric addrExpr = [=]() -> ExprValue { return {&osd->osec, false, 0, ""}; };
595aca2e42cSDimitry Andric }
596145449b1SDimitry Andric v.push_back(osd);
597145449b1SDimitry Andric prev = &osd->osec;
59820d35e67SDimitry Andric }
59920d35e67SDimitry Andric
60020d35e67SDimitry Andric // According to the specification, at the end of the overlay, the location
60120d35e67SDimitry Andric // counter should be equal to the overlay base address plus size of the
60220d35e67SDimitry Andric // largest section seen in the overlay.
60320d35e67SDimitry Andric // Here we want to create the Dot assignment command to achieve that.
604f1e1c239SDimitry Andric Expr moveDot = [=] {
605f1e1c239SDimitry Andric uint64_t max = 0;
606f65dcba8SDimitry Andric for (SectionCommand *cmd : v)
607145449b1SDimitry Andric max = std::max(max, cast<OutputDesc>(cmd)->osec.size);
608f1e1c239SDimitry Andric return addrExpr().getValue() + max;
60920d35e67SDimitry Andric };
610b1c73532SDimitry Andric v.push_back(make<SymbolAssignment>(".", moveDot, 0, getCurrentLocation()));
611f1e1c239SDimitry Andric return v;
61220d35e67SDimitry Andric }
61320d35e67SDimitry Andric
readOverwriteSections()614344a3780SDimitry Andric void ScriptParser::readOverwriteSections() {
615344a3780SDimitry Andric expect("{");
616344a3780SDimitry Andric while (!errorCount() && !consume("}"))
617344a3780SDimitry Andric script->overwriteSections.push_back(readOutputSectionDescription(next()));
618344a3780SDimitry Andric }
619344a3780SDimitry Andric
readSections()620d2d3ebb8SDimitry Andric void ScriptParser::readSections() {
621d2d3ebb8SDimitry Andric expect("{");
6226f8fc217SDimitry Andric SmallVector<SectionCommand *, 0> v;
623eb1ff93dSDimitry Andric while (!errorCount() && !consume("}")) {
624f1e1c239SDimitry Andric StringRef tok = next();
625f1e1c239SDimitry Andric if (tok == "OVERLAY") {
626f65dcba8SDimitry Andric for (SectionCommand *cmd : readOverlay())
627f1e1c239SDimitry Andric v.push_back(cmd);
62820d35e67SDimitry Andric continue;
629f1e1c239SDimitry Andric } else if (tok == "INCLUDE") {
630e2fd426bSDimitry Andric readInclude();
631e2fd426bSDimitry Andric continue;
63220d35e67SDimitry Andric }
63320d35e67SDimitry Andric
634f65dcba8SDimitry Andric if (SectionCommand *cmd = readAssignment(tok))
635f1e1c239SDimitry Andric v.push_back(cmd);
636d2d3ebb8SDimitry Andric else
637f1e1c239SDimitry Andric v.push_back(readOutputSectionDescription(tok));
638d2d3ebb8SDimitry Andric }
639145449b1SDimitry Andric
640145449b1SDimitry Andric // If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN,
641145449b1SDimitry Andric // the relro fields should be cleared.
642b1c73532SDimitry Andric if (!script->seenRelroEnd)
643145449b1SDimitry Andric for (SectionCommand *cmd : v)
644145449b1SDimitry Andric if (auto *osd = dyn_cast<OutputDesc>(cmd))
645145449b1SDimitry Andric osd->osec.relro = false;
646145449b1SDimitry Andric
647cfca06d7SDimitry Andric script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),
648cfca06d7SDimitry Andric v.end());
64920d35e67SDimitry Andric
650cfca06d7SDimitry Andric if (atEOF() || !consume("INSERT")) {
651cfca06d7SDimitry Andric script->hasSectionsCommand = true;
65220d35e67SDimitry Andric return;
653d2d3ebb8SDimitry Andric }
65420d35e67SDimitry Andric
655cfca06d7SDimitry Andric bool isAfter = false;
656cfca06d7SDimitry Andric if (consume("AFTER"))
657cfca06d7SDimitry Andric isAfter = true;
658cfca06d7SDimitry Andric else if (!consume("BEFORE"))
659cfca06d7SDimitry Andric setError("expected AFTER/BEFORE, but got '" + next() + "'");
660cfca06d7SDimitry Andric StringRef where = next();
6616f8fc217SDimitry Andric SmallVector<StringRef, 0> names;
662f65dcba8SDimitry Andric for (SectionCommand *cmd : v)
663145449b1SDimitry Andric if (auto *os = dyn_cast<OutputDesc>(cmd))
664145449b1SDimitry Andric names.push_back(os->osec.name);
665344a3780SDimitry Andric if (!names.empty())
666344a3780SDimitry Andric script->insertCommands.push_back({std::move(names), isAfter, where});
667d2d3ebb8SDimitry Andric }
668d2d3ebb8SDimitry Andric
readTarget()669e2fd426bSDimitry Andric void ScriptParser::readTarget() {
670e2fd426bSDimitry Andric // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
671e2fd426bSDimitry Andric // we accept only a limited set of BFD names (i.e. "elf" or "binary")
672e2fd426bSDimitry Andric // for --format. We recognize only /^elf/ and "binary" in the linker
673e2fd426bSDimitry Andric // script as well.
674e2fd426bSDimitry Andric expect("(");
675145449b1SDimitry Andric StringRef tok = unquote(next());
676e2fd426bSDimitry Andric expect(")");
677e2fd426bSDimitry Andric
6787fa27ce4SDimitry Andric if (tok.starts_with("elf"))
679f1e1c239SDimitry Andric config->formatBinary = false;
680f1e1c239SDimitry Andric else if (tok == "binary")
681f1e1c239SDimitry Andric config->formatBinary = true;
682e2fd426bSDimitry Andric else
683f1e1c239SDimitry Andric setError("unknown target: " + tok);
684e2fd426bSDimitry Andric }
685e2fd426bSDimitry Andric
precedence(StringRef op)686f1e1c239SDimitry Andric static int precedence(StringRef op) {
687f1e1c239SDimitry Andric return StringSwitch<int>(op)
6887fa27ce4SDimitry Andric .Cases("*", "/", "%", 11)
6897fa27ce4SDimitry Andric .Cases("+", "-", 10)
6907fa27ce4SDimitry Andric .Cases("<<", ">>", 9)
6917fa27ce4SDimitry Andric .Cases("<", "<=", ">", ">=", 8)
6927fa27ce4SDimitry Andric .Cases("==", "!=", 7)
6937fa27ce4SDimitry Andric .Case("&", 6)
6947fa27ce4SDimitry Andric .Case("^", 5)
695145449b1SDimitry Andric .Case("|", 4)
696145449b1SDimitry Andric .Case("&&", 3)
697145449b1SDimitry Andric .Case("||", 2)
698145449b1SDimitry Andric .Case("?", 1)
699d2d3ebb8SDimitry Andric .Default(-1);
700d2d3ebb8SDimitry Andric }
701d2d3ebb8SDimitry Andric
readFilePatterns()702d2d3ebb8SDimitry Andric StringMatcher ScriptParser::readFilePatterns() {
703cfca06d7SDimitry Andric StringMatcher Matcher;
704cfca06d7SDimitry Andric
705eb1ff93dSDimitry Andric while (!errorCount() && !consume(")"))
706cfca06d7SDimitry Andric Matcher.addPattern(SingleStringMatcher(next()));
707cfca06d7SDimitry Andric return Matcher;
708d2d3ebb8SDimitry Andric }
709d2d3ebb8SDimitry Andric
peekSortKind()710b60736ecSDimitry Andric SortSectionPolicy ScriptParser::peekSortKind() {
711b60736ecSDimitry Andric return StringSwitch<SortSectionPolicy>(peek())
7127fa27ce4SDimitry Andric .Case("REVERSE", SortSectionPolicy::Reverse)
713b60736ecSDimitry Andric .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)
714b60736ecSDimitry Andric .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)
715b60736ecSDimitry Andric .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)
716b60736ecSDimitry Andric .Case("SORT_NONE", SortSectionPolicy::None)
717b60736ecSDimitry Andric .Default(SortSectionPolicy::Default);
718b60736ecSDimitry Andric }
719b60736ecSDimitry Andric
readSortKind()720d2d3ebb8SDimitry Andric SortSectionPolicy ScriptParser::readSortKind() {
721b60736ecSDimitry Andric SortSectionPolicy ret = peekSortKind();
722b60736ecSDimitry Andric if (ret != SortSectionPolicy::Default)
723b60736ecSDimitry Andric skip();
724b60736ecSDimitry Andric return ret;
725d2d3ebb8SDimitry Andric }
726d2d3ebb8SDimitry Andric
727d2d3ebb8SDimitry Andric // Reads SECTIONS command contents in the following form:
728d2d3ebb8SDimitry Andric //
729d2d3ebb8SDimitry Andric // <contents> ::= <elem>*
730d2d3ebb8SDimitry Andric // <elem> ::= <exclude>? <glob-pattern>
731d2d3ebb8SDimitry Andric // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
732d2d3ebb8SDimitry Andric //
733d2d3ebb8SDimitry Andric // For example,
734d2d3ebb8SDimitry Andric //
735d2d3ebb8SDimitry Andric // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
736d2d3ebb8SDimitry Andric //
737d2d3ebb8SDimitry Andric // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
738d2d3ebb8SDimitry Andric // The semantics of that is section .foo in any file, section .bar in
739d2d3ebb8SDimitry Andric // any file but a.o, and section .baz in any file but b.o.
readInputSectionsList()7406f8fc217SDimitry Andric SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() {
7416f8fc217SDimitry Andric SmallVector<SectionPattern, 0> ret;
742eb1ff93dSDimitry Andric while (!errorCount() && peek() != ")") {
743f1e1c239SDimitry Andric StringMatcher excludeFilePat;
744d2d3ebb8SDimitry Andric if (consume("EXCLUDE_FILE")) {
745d2d3ebb8SDimitry Andric expect("(");
746f1e1c239SDimitry Andric excludeFilePat = readFilePatterns();
747d2d3ebb8SDimitry Andric }
748d2d3ebb8SDimitry Andric
749cfca06d7SDimitry Andric StringMatcher SectionMatcher;
750b60736ecSDimitry Andric // Break if the next token is ), EXCLUDE_FILE, or SORT*.
751ac9a064cSDimitry Andric while (!errorCount() && peekSortKind() == SortSectionPolicy::Default) {
752ac9a064cSDimitry Andric StringRef s = peek();
753ac9a064cSDimitry Andric if (s == ")" || s == "EXCLUDE_FILE")
754ac9a064cSDimitry Andric break;
755ac9a064cSDimitry Andric // Detect common mistakes when certain non-wildcard meta characters are
756ac9a064cSDimitry Andric // used without a closing ')'.
757ac9a064cSDimitry Andric if (!s.empty() && strchr("(){}", s[0])) {
758ac9a064cSDimitry Andric skip();
759ac9a064cSDimitry Andric setError("section pattern is expected");
760ac9a064cSDimitry Andric break;
761ac9a064cSDimitry Andric }
762cfca06d7SDimitry Andric SectionMatcher.addPattern(unquote(next()));
763ac9a064cSDimitry Andric }
764d2d3ebb8SDimitry Andric
765cfca06d7SDimitry Andric if (!SectionMatcher.empty())
766cfca06d7SDimitry Andric ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
767b60736ecSDimitry Andric else if (excludeFilePat.empty())
768b60736ecSDimitry Andric break;
769d2d3ebb8SDimitry Andric else
770d2d3ebb8SDimitry Andric setError("section pattern is expected");
771d2d3ebb8SDimitry Andric }
772f1e1c239SDimitry Andric return ret;
773d2d3ebb8SDimitry Andric }
774d2d3ebb8SDimitry Andric
775d2d3ebb8SDimitry Andric // Reads contents of "SECTIONS" directive. That directive contains a
776d2d3ebb8SDimitry Andric // list of glob patterns for input sections. The grammar is as follows.
777d2d3ebb8SDimitry Andric //
778d2d3ebb8SDimitry Andric // <patterns> ::= <section-list>
779d2d3ebb8SDimitry Andric // | <sort> "(" <section-list> ")"
780d2d3ebb8SDimitry Andric // | <sort> "(" <sort> "(" <section-list> ")" ")"
781d2d3ebb8SDimitry Andric //
782d2d3ebb8SDimitry Andric // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
783d2d3ebb8SDimitry Andric // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
784d2d3ebb8SDimitry Andric //
785d2d3ebb8SDimitry Andric // <section-list> is parsed by readInputSectionsList().
786d2d3ebb8SDimitry Andric InputSectionDescription *
readInputSectionRules(StringRef filePattern,uint64_t withFlags,uint64_t withoutFlags)787cfca06d7SDimitry Andric ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
788cfca06d7SDimitry Andric uint64_t withoutFlags) {
789cfca06d7SDimitry Andric auto *cmd =
790cfca06d7SDimitry Andric make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
791d2d3ebb8SDimitry Andric expect("(");
792d2d3ebb8SDimitry Andric
793eb1ff93dSDimitry Andric while (!errorCount() && !consume(")")) {
794f1e1c239SDimitry Andric SortSectionPolicy outer = readSortKind();
795f1e1c239SDimitry Andric SortSectionPolicy inner = SortSectionPolicy::Default;
7966f8fc217SDimitry Andric SmallVector<SectionPattern, 0> v;
797f1e1c239SDimitry Andric if (outer != SortSectionPolicy::Default) {
798d2d3ebb8SDimitry Andric expect("(");
799f1e1c239SDimitry Andric inner = readSortKind();
800f1e1c239SDimitry Andric if (inner != SortSectionPolicy::Default) {
801d2d3ebb8SDimitry Andric expect("(");
802f1e1c239SDimitry Andric v = readInputSectionsList();
803d2d3ebb8SDimitry Andric expect(")");
804d2d3ebb8SDimitry Andric } else {
805f1e1c239SDimitry Andric v = readInputSectionsList();
806d2d3ebb8SDimitry Andric }
807d2d3ebb8SDimitry Andric expect(")");
808d2d3ebb8SDimitry Andric } else {
809f1e1c239SDimitry Andric v = readInputSectionsList();
810d2d3ebb8SDimitry Andric }
811d2d3ebb8SDimitry Andric
812f1e1c239SDimitry Andric for (SectionPattern &pat : v) {
813f1e1c239SDimitry Andric pat.sortInner = inner;
814f1e1c239SDimitry Andric pat.sortOuter = outer;
815d2d3ebb8SDimitry Andric }
816d2d3ebb8SDimitry Andric
817f1e1c239SDimitry Andric std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
818d2d3ebb8SDimitry Andric }
819f1e1c239SDimitry Andric return cmd;
820d2d3ebb8SDimitry Andric }
821d2d3ebb8SDimitry Andric
822d2d3ebb8SDimitry Andric InputSectionDescription *
readInputSectionDescription(StringRef tok)823f1e1c239SDimitry Andric ScriptParser::readInputSectionDescription(StringRef tok) {
824d2d3ebb8SDimitry Andric // Input section wildcard can be surrounded by KEEP.
825d2d3ebb8SDimitry Andric // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
826cfca06d7SDimitry Andric uint64_t withFlags = 0;
827cfca06d7SDimitry Andric uint64_t withoutFlags = 0;
828f1e1c239SDimitry Andric if (tok == "KEEP") {
829d2d3ebb8SDimitry Andric expect("(");
830cfca06d7SDimitry Andric if (consume("INPUT_SECTION_FLAGS"))
831cfca06d7SDimitry Andric std::tie(withFlags, withoutFlags) = readInputSectionFlags();
832cfca06d7SDimitry Andric InputSectionDescription *cmd =
833cfca06d7SDimitry Andric readInputSectionRules(next(), withFlags, withoutFlags);
834d2d3ebb8SDimitry Andric expect(")");
835f1e1c239SDimitry Andric script->keptSections.push_back(cmd);
836f1e1c239SDimitry Andric return cmd;
837d2d3ebb8SDimitry Andric }
838cfca06d7SDimitry Andric if (tok == "INPUT_SECTION_FLAGS") {
839cfca06d7SDimitry Andric std::tie(withFlags, withoutFlags) = readInputSectionFlags();
840cfca06d7SDimitry Andric tok = next();
841cfca06d7SDimitry Andric }
842cfca06d7SDimitry Andric return readInputSectionRules(tok, withFlags, withoutFlags);
843d2d3ebb8SDimitry Andric }
844d2d3ebb8SDimitry Andric
readSort()845d2d3ebb8SDimitry Andric void ScriptParser::readSort() {
846d2d3ebb8SDimitry Andric expect("(");
847d2d3ebb8SDimitry Andric expect("CONSTRUCTORS");
848d2d3ebb8SDimitry Andric expect(")");
849d2d3ebb8SDimitry Andric }
850d2d3ebb8SDimitry Andric
readAssert()85120d35e67SDimitry Andric Expr ScriptParser::readAssert() {
852d2d3ebb8SDimitry Andric expect("(");
853f1e1c239SDimitry Andric Expr e = readExpr();
854d2d3ebb8SDimitry Andric expect(",");
855f1e1c239SDimitry Andric StringRef msg = unquote(next());
856d2d3ebb8SDimitry Andric expect(")");
857d2d3ebb8SDimitry Andric
858d2d3ebb8SDimitry Andric return [=] {
859f1e1c239SDimitry Andric if (!e().getValue())
860d2bd9e70SDimitry Andric errorOrWarn(msg);
861f1e1c239SDimitry Andric return script->getDot();
862d2d3ebb8SDimitry Andric };
863d2d3ebb8SDimitry Andric }
864d2d3ebb8SDimitry Andric
865145449b1SDimitry Andric #define ECase(X) \
866145449b1SDimitry Andric { #X, X }
867145449b1SDimitry Andric constexpr std::pair<const char *, unsigned> typeMap[] = {
868145449b1SDimitry Andric ECase(SHT_PROGBITS), ECase(SHT_NOTE), ECase(SHT_NOBITS),
869145449b1SDimitry Andric ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY),
870145449b1SDimitry Andric };
871145449b1SDimitry Andric #undef ECase
872145449b1SDimitry Andric
873e2fd426bSDimitry Andric // Tries to read the special directive for an output section definition which
874145449b1SDimitry Andric // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
875145449b1SDimitry Andric // "(TYPE=<value>)".
readSectionDirective(OutputSection * cmd,StringRef tok)876ac9a064cSDimitry Andric bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok) {
877ac9a064cSDimitry Andric if (tok != "NOLOAD" && tok != "COPY" && tok != "INFO" && tok != "OVERLAY" &&
878ac9a064cSDimitry Andric tok != "TYPE")
879e2fd426bSDimitry Andric return false;
880e2fd426bSDimitry Andric
881e2fd426bSDimitry Andric if (consume("NOLOAD")) {
882cfca06d7SDimitry Andric cmd->type = SHT_NOBITS;
883145449b1SDimitry Andric cmd->typeIsSet = true;
884145449b1SDimitry Andric } else if (consume("TYPE")) {
885145449b1SDimitry Andric expect("=");
886145449b1SDimitry Andric StringRef value = peek();
887145449b1SDimitry Andric auto it = llvm::find_if(typeMap, [=](auto e) { return e.first == value; });
888145449b1SDimitry Andric if (it != std::end(typeMap)) {
889145449b1SDimitry Andric // The value is a recognized literal SHT_*.
890145449b1SDimitry Andric cmd->type = it->second;
891145449b1SDimitry Andric skip();
8927fa27ce4SDimitry Andric } else if (value.starts_with("SHT_")) {
893145449b1SDimitry Andric setError("unknown section type " + value);
894145449b1SDimitry Andric } else {
895145449b1SDimitry Andric // Otherwise, read an expression.
896145449b1SDimitry Andric cmd->type = readExpr()().getValue();
897145449b1SDimitry Andric }
898145449b1SDimitry Andric cmd->typeIsSet = true;
899e2fd426bSDimitry Andric } else {
900e2fd426bSDimitry Andric skip(); // This is "COPY", "INFO" or "OVERLAY".
901f1e1c239SDimitry Andric cmd->nonAlloc = true;
902e2fd426bSDimitry Andric }
903e2fd426bSDimitry Andric expect(")");
904e2fd426bSDimitry Andric return true;
905e2fd426bSDimitry Andric }
906e2fd426bSDimitry Andric
90720d35e67SDimitry Andric // Reads an expression and/or the special directive for an output
90820d35e67SDimitry Andric // section definition. Directive is one of following: "(NOLOAD)",
90920d35e67SDimitry Andric // "(COPY)", "(INFO)" or "(OVERLAY)".
9102079716dSDimitry Andric //
9112079716dSDimitry Andric // An output section name can be followed by an address expression
91220d35e67SDimitry Andric // and/or directive. This grammar is not LL(1) because "(" can be
91320d35e67SDimitry Andric // interpreted as either the beginning of some expression or beginning
91420d35e67SDimitry Andric // of directive.
9152079716dSDimitry Andric //
9162079716dSDimitry Andric // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
9172079716dSDimitry Andric // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
readSectionAddressType(OutputSection * cmd)918f1e1c239SDimitry Andric void ScriptParser::readSectionAddressType(OutputSection *cmd) {
919ac9a064cSDimitry Andric if (consume("(")) {
920145449b1SDimitry Andric // Temporarily set inExpr to support TYPE=<value> without spaces.
921ac9a064cSDimitry Andric SaveAndRestore saved(inExpr, true);
922ac9a064cSDimitry Andric if (readSectionDirective(cmd, peek()))
9232079716dSDimitry Andric return;
924f1e1c239SDimitry Andric cmd->addrExpr = readExpr();
925ac9a064cSDimitry Andric expect(")");
926ac9a064cSDimitry Andric } else {
927ac9a064cSDimitry Andric cmd->addrExpr = readExpr();
928ac9a064cSDimitry Andric }
929ac9a064cSDimitry Andric
930ac9a064cSDimitry Andric if (consume("(")) {
931ac9a064cSDimitry Andric SaveAndRestore saved(inExpr, true);
932ac9a064cSDimitry Andric StringRef tok = peek();
933ac9a064cSDimitry Andric if (!readSectionDirective(cmd, tok))
934ac9a064cSDimitry Andric setError("unknown section directive: " + tok);
935ac9a064cSDimitry Andric }
9362079716dSDimitry Andric }
9372079716dSDimitry Andric
checkAlignment(Expr e,std::string & loc)938f1e1c239SDimitry Andric static Expr checkAlignment(Expr e, std::string &loc) {
939eb1ff93dSDimitry Andric return [=] {
940f1e1c239SDimitry Andric uint64_t alignment = std::max((uint64_t)1, e().getValue());
941f1e1c239SDimitry Andric if (!isPowerOf2_64(alignment)) {
942f1e1c239SDimitry Andric error(loc + ": alignment must be power of 2");
943eb1ff93dSDimitry Andric return (uint64_t)1; // Return a dummy value.
944eb1ff93dSDimitry Andric }
945f1e1c239SDimitry Andric return alignment;
946eb1ff93dSDimitry Andric };
947eb1ff93dSDimitry Andric }
948eb1ff93dSDimitry Andric
readOverlaySectionDescription()949145449b1SDimitry Andric OutputDesc *ScriptParser::readOverlaySectionDescription() {
950145449b1SDimitry Andric OutputDesc *osd = script->createOutputSection(next(), getCurrentLocation());
951145449b1SDimitry Andric osd->osec.inOverlay = true;
95220d35e67SDimitry Andric expect("{");
953cfca06d7SDimitry Andric while (!errorCount() && !consume("}")) {
954cfca06d7SDimitry Andric uint64_t withFlags = 0;
955cfca06d7SDimitry Andric uint64_t withoutFlags = 0;
956cfca06d7SDimitry Andric if (consume("INPUT_SECTION_FLAGS"))
957cfca06d7SDimitry Andric std::tie(withFlags, withoutFlags) = readInputSectionFlags();
958145449b1SDimitry Andric osd->osec.commands.push_back(
959cfca06d7SDimitry Andric readInputSectionRules(next(), withFlags, withoutFlags));
960cfca06d7SDimitry Andric }
9617fa27ce4SDimitry Andric osd->osec.phdrs = readOutputSectionPhdrs();
962145449b1SDimitry Andric return osd;
96320d35e67SDimitry Andric }
96420d35e67SDimitry Andric
readOutputSectionDescription(StringRef outSec)965145449b1SDimitry Andric OutputDesc *ScriptParser::readOutputSectionDescription(StringRef outSec) {
9667fa27ce4SDimitry Andric OutputDesc *cmd =
9677fa27ce4SDimitry Andric script->createOutputSection(unquote(outSec), getCurrentLocation());
968145449b1SDimitry Andric OutputSection *osec = &cmd->osec;
969145449b1SDimitry Andric // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.
970b1c73532SDimitry Andric osec->relro = script->seenDataAlign && !script->seenRelroEnd;
971d2d3ebb8SDimitry Andric
972f1e1c239SDimitry Andric size_t symbolsReferenced = script->referencedSymbols.size();
97320d35e67SDimitry Andric
974d2d3ebb8SDimitry Andric if (peek() != ":")
975145449b1SDimitry Andric readSectionAddressType(osec);
976d2d3ebb8SDimitry Andric expect(":");
977d2d3ebb8SDimitry Andric
978f1e1c239SDimitry Andric std::string location = getCurrentLocation();
979d2d3ebb8SDimitry Andric if (consume("AT"))
980145449b1SDimitry Andric osec->lmaExpr = readParenExpr();
981d2d3ebb8SDimitry Andric if (consume("ALIGN"))
982145449b1SDimitry Andric osec->alignExpr = checkAlignment(readParenExpr(), location);
983d2d3ebb8SDimitry Andric if (consume("SUBALIGN"))
984145449b1SDimitry Andric osec->subalignExpr = checkAlignment(readParenExpr(), location);
985d2d3ebb8SDimitry Andric
986d2d3ebb8SDimitry Andric // Parse constraints.
987d2d3ebb8SDimitry Andric if (consume("ONLY_IF_RO"))
988145449b1SDimitry Andric osec->constraint = ConstraintKind::ReadOnly;
989d2d3ebb8SDimitry Andric if (consume("ONLY_IF_RW"))
990145449b1SDimitry Andric osec->constraint = ConstraintKind::ReadWrite;
991d2d3ebb8SDimitry Andric expect("{");
992d2d3ebb8SDimitry Andric
993eb1ff93dSDimitry Andric while (!errorCount() && !consume("}")) {
994f1e1c239SDimitry Andric StringRef tok = next();
995f1e1c239SDimitry Andric if (tok == ";") {
996d2d3ebb8SDimitry Andric // Empty commands are allowed. Do nothing here.
997f1e1c239SDimitry Andric } else if (SymbolAssignment *assign = readAssignment(tok)) {
998145449b1SDimitry Andric osec->commands.push_back(assign);
999f1e1c239SDimitry Andric } else if (ByteCommand *data = readByteCommand(tok)) {
1000145449b1SDimitry Andric osec->commands.push_back(data);
1001f1e1c239SDimitry Andric } else if (tok == "CONSTRUCTORS") {
1002d2d3ebb8SDimitry Andric // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1003d2d3ebb8SDimitry Andric // by name. This is for very old file formats such as ECOFF/XCOFF.
1004d2d3ebb8SDimitry Andric // For ELF, we should ignore.
1005f1e1c239SDimitry Andric } else if (tok == "FILL") {
1006f1e1c239SDimitry Andric // We handle the FILL command as an alias for =fillexp section attribute,
1007f1e1c239SDimitry Andric // which is different from what GNU linkers do.
1008f1e1c239SDimitry Andric // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1009cfca06d7SDimitry Andric if (peek() != "(")
1010cfca06d7SDimitry Andric setError("( expected, but got " + peek());
1011145449b1SDimitry Andric osec->filler = readFill();
1012f1e1c239SDimitry Andric } else if (tok == "SORT") {
1013d2d3ebb8SDimitry Andric readSort();
1014f1e1c239SDimitry Andric } else if (tok == "INCLUDE") {
1015e2fd426bSDimitry Andric readInclude();
1016145449b1SDimitry Andric } else if (tok == "(" || tok == ")") {
1017145449b1SDimitry Andric setError("expected filename pattern");
1018d2d3ebb8SDimitry Andric } else if (peek() == "(") {
1019145449b1SDimitry Andric osec->commands.push_back(readInputSectionDescription(tok));
1020d2d3ebb8SDimitry Andric } else {
1021e2fd426bSDimitry Andric // We have a file name and no input sections description. It is not a
1022e2fd426bSDimitry Andric // commonly used syntax, but still acceptable. In that case, all sections
1023e2fd426bSDimitry Andric // from the file will be included.
1024cfca06d7SDimitry Andric // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
1025cfca06d7SDimitry Andric // handle this case here as it will already have been matched by the
1026cfca06d7SDimitry Andric // case above.
1027f1e1c239SDimitry Andric auto *isd = make<InputSectionDescription>(tok);
1028cfca06d7SDimitry Andric isd->sectionPatterns.push_back({{}, StringMatcher("*")});
1029145449b1SDimitry Andric osec->commands.push_back(isd);
1030d2d3ebb8SDimitry Andric }
1031d2d3ebb8SDimitry Andric }
1032d2d3ebb8SDimitry Andric
1033d2d3ebb8SDimitry Andric if (consume(">"))
1034145449b1SDimitry Andric osec->memoryRegionName = std::string(next());
1035d2d3ebb8SDimitry Andric
103620d35e67SDimitry Andric if (consume("AT")) {
103720d35e67SDimitry Andric expect(">");
1038145449b1SDimitry Andric osec->lmaRegionName = std::string(next());
103920d35e67SDimitry Andric }
104020d35e67SDimitry Andric
1041145449b1SDimitry Andric if (osec->lmaExpr && !osec->lmaRegionName.empty())
104220d35e67SDimitry Andric error("section can't have both LMA and a load region");
104320d35e67SDimitry Andric
1044145449b1SDimitry Andric osec->phdrs = readOutputSectionPhdrs();
1045d2d3ebb8SDimitry Andric
10467fa27ce4SDimitry Andric if (peek() == "=" || peek().starts_with("=")) {
1047f1e1c239SDimitry Andric inExpr = true;
1048f1e1c239SDimitry Andric consume("=");
1049145449b1SDimitry Andric osec->filler = readFill();
1050f1e1c239SDimitry Andric inExpr = false;
1051f1e1c239SDimitry Andric }
1052d2d3ebb8SDimitry Andric
1053d2d3ebb8SDimitry Andric // Consume optional comma following output section command.
1054d2d3ebb8SDimitry Andric consume(",");
1055d2d3ebb8SDimitry Andric
1056f1e1c239SDimitry Andric if (script->referencedSymbols.size() > symbolsReferenced)
1057145449b1SDimitry Andric osec->expressionsUseSymbols = true;
1058f1e1c239SDimitry Andric return cmd;
1059d2d3ebb8SDimitry Andric }
1060d2d3ebb8SDimitry Andric
1061f1e1c239SDimitry Andric // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
1062d2d3ebb8SDimitry Andric // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1063f1e1c239SDimitry Andric // We do not support using symbols in such expressions.
1064d2d3ebb8SDimitry Andric //
1065d2d3ebb8SDimitry Andric // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
1066d2d3ebb8SDimitry Andric // size, while ld.gold always handles it as a 32-bit big-endian number.
1067d2d3ebb8SDimitry Andric // We are compatible with ld.gold because it's easier to implement.
1068cfca06d7SDimitry Andric // Also, we require that expressions with operators must be wrapped into
1069cfca06d7SDimitry Andric // round brackets. We did it to resolve the ambiguity when parsing scripts like:
1070cfca06d7SDimitry Andric // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
readFill()1071f1e1c239SDimitry Andric std::array<uint8_t, 4> ScriptParser::readFill() {
1072cfca06d7SDimitry Andric uint64_t value = readPrimary()().val;
1073f1e1c239SDimitry Andric if (value > UINT32_MAX)
1074f1e1c239SDimitry Andric setError("filler expression result does not fit 32-bit: 0x" +
1075f1e1c239SDimitry Andric Twine::utohexstr(value));
1076d2d3ebb8SDimitry Andric
1077f1e1c239SDimitry Andric std::array<uint8_t, 4> buf;
1078f1e1c239SDimitry Andric write32be(buf.data(), (uint32_t)value);
1079f1e1c239SDimitry Andric return buf;
1080d2d3ebb8SDimitry Andric }
1081d2d3ebb8SDimitry Andric
readProvideHidden(bool provide,bool hidden)1082f1e1c239SDimitry Andric SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
1083d2d3ebb8SDimitry Andric expect("(");
1084145449b1SDimitry Andric StringRef name = next(), eq = peek();
1085145449b1SDimitry Andric if (eq != "=") {
1086145449b1SDimitry Andric setError("= expected, but got " + next());
1087145449b1SDimitry Andric while (!atEOF() && next() != ")")
1088145449b1SDimitry Andric ;
1089145449b1SDimitry Andric return nullptr;
1090145449b1SDimitry Andric }
1091ac9a064cSDimitry Andric llvm::SaveAndRestore saveActiveProvideSym(activeProvideSym);
1092ac9a064cSDimitry Andric if (provide)
1093ac9a064cSDimitry Andric activeProvideSym = name;
1094145449b1SDimitry Andric SymbolAssignment *cmd = readSymbolAssignment(name);
1095f1e1c239SDimitry Andric cmd->provide = provide;
1096f1e1c239SDimitry Andric cmd->hidden = hidden;
1097d2d3ebb8SDimitry Andric expect(")");
1098f1e1c239SDimitry Andric return cmd;
1099d2d3ebb8SDimitry Andric }
1100d2d3ebb8SDimitry Andric
readAssignment(StringRef tok)1101f1e1c239SDimitry Andric SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
110220d35e67SDimitry Andric // Assert expression returns Dot, so this is equal to ".=."
1103f1e1c239SDimitry Andric if (tok == "ASSERT")
1104b1c73532SDimitry Andric return make<SymbolAssignment>(".", readAssert(), 0, getCurrentLocation());
110520d35e67SDimitry Andric
1106f1e1c239SDimitry Andric size_t oldPos = pos;
1107f1e1c239SDimitry Andric SymbolAssignment *cmd = nullptr;
1108b1c73532SDimitry Andric bool savedSeenRelroEnd = script->seenRelroEnd;
1109145449b1SDimitry Andric const StringRef op = peek();
11107fa27ce4SDimitry Andric if (op.starts_with("=")) {
1111145449b1SDimitry Andric // Support = followed by an expression without whitespace.
1112e3b55780SDimitry Andric SaveAndRestore saved(inExpr, true);
1113f1e1c239SDimitry Andric cmd = readSymbolAssignment(tok);
11147fa27ce4SDimitry Andric } else if ((op.size() == 2 && op[1] == '=' && strchr("*/+-&^|", op[0])) ||
1115145449b1SDimitry Andric op == "<<=" || op == ">>=") {
1116145449b1SDimitry Andric cmd = readSymbolAssignment(tok);
1117145449b1SDimitry Andric } else if (tok == "PROVIDE") {
1118e3b55780SDimitry Andric SaveAndRestore saved(inExpr, true);
1119f1e1c239SDimitry Andric cmd = readProvideHidden(true, false);
1120145449b1SDimitry Andric } else if (tok == "HIDDEN") {
1121e3b55780SDimitry Andric SaveAndRestore saved(inExpr, true);
1122f1e1c239SDimitry Andric cmd = readProvideHidden(false, true);
1123145449b1SDimitry Andric } else if (tok == "PROVIDE_HIDDEN") {
1124e3b55780SDimitry Andric SaveAndRestore saved(inExpr, true);
1125f1e1c239SDimitry Andric cmd = readProvideHidden(true, true);
1126145449b1SDimitry Andric }
112720d35e67SDimitry Andric
1128f1e1c239SDimitry Andric if (cmd) {
1129b1c73532SDimitry Andric cmd->dataSegmentRelroEnd = !savedSeenRelroEnd && script->seenRelroEnd;
1130f1e1c239SDimitry Andric cmd->commandString =
1131f1e1c239SDimitry Andric tok.str() + " " +
1132f1e1c239SDimitry Andric llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
113320d35e67SDimitry Andric expect(";");
1134d2d3ebb8SDimitry Andric }
1135f1e1c239SDimitry Andric return cmd;
1136d2d3ebb8SDimitry Andric }
1137d2d3ebb8SDimitry Andric
readSymbolAssignment(StringRef name)1138f1e1c239SDimitry Andric SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1139344a3780SDimitry Andric name = unquote(name);
1140f1e1c239SDimitry Andric StringRef op = next();
1141145449b1SDimitry Andric assert(op == "=" || op == "*=" || op == "/=" || op == "+=" || op == "-=" ||
11427fa27ce4SDimitry Andric op == "&=" || op == "^=" || op == "|=" || op == "<<=" || op == ">>=");
1143b1c73532SDimitry Andric // Note: GNU ld does not support %=.
1144f1e1c239SDimitry Andric Expr e = readExpr();
1145145449b1SDimitry Andric if (op != "=") {
1146f1e1c239SDimitry Andric std::string loc = getCurrentLocation();
1147145449b1SDimitry Andric e = [=, c = op[0]]() -> ExprValue {
1148145449b1SDimitry Andric ExprValue lhs = script->getSymbolValue(name, loc);
1149145449b1SDimitry Andric switch (c) {
1150145449b1SDimitry Andric case '*':
1151145449b1SDimitry Andric return lhs.getValue() * e().getValue();
1152145449b1SDimitry Andric case '/':
1153145449b1SDimitry Andric if (uint64_t rv = e().getValue())
1154145449b1SDimitry Andric return lhs.getValue() / rv;
1155145449b1SDimitry Andric error(loc + ": division by zero");
1156145449b1SDimitry Andric return 0;
1157145449b1SDimitry Andric case '+':
1158145449b1SDimitry Andric return add(lhs, e());
1159145449b1SDimitry Andric case '-':
1160145449b1SDimitry Andric return sub(lhs, e());
1161145449b1SDimitry Andric case '<':
11627fa27ce4SDimitry Andric return lhs.getValue() << e().getValue() % 64;
1163145449b1SDimitry Andric case '>':
11647fa27ce4SDimitry Andric return lhs.getValue() >> e().getValue() % 64;
1165145449b1SDimitry Andric case '&':
1166145449b1SDimitry Andric return lhs.getValue() & e().getValue();
11677fa27ce4SDimitry Andric case '^':
11687fa27ce4SDimitry Andric return lhs.getValue() ^ e().getValue();
1169145449b1SDimitry Andric case '|':
1170145449b1SDimitry Andric return lhs.getValue() | e().getValue();
1171145449b1SDimitry Andric default:
1172145449b1SDimitry Andric llvm_unreachable("");
1173145449b1SDimitry Andric }
1174145449b1SDimitry Andric };
1175d2d3ebb8SDimitry Andric }
1176b1c73532SDimitry Andric return make<SymbolAssignment>(name, e, ctx.scriptSymOrderCounter++,
1177b1c73532SDimitry Andric getCurrentLocation());
1178d2d3ebb8SDimitry Andric }
1179d2d3ebb8SDimitry Andric
1180d2d3ebb8SDimitry Andric // This is an operator-precedence parser to parse a linker
1181d2d3ebb8SDimitry Andric // script expression.
readExpr()1182d2d3ebb8SDimitry Andric Expr ScriptParser::readExpr() {
1183d2d3ebb8SDimitry Andric // Our lexer is context-aware. Set the in-expression bit so that
1184d2d3ebb8SDimitry Andric // they apply different tokenization rules.
1185ac9a064cSDimitry Andric SaveAndRestore saved(inExpr, true);
1186f1e1c239SDimitry Andric Expr e = readExpr1(readPrimary(), 0);
1187f1e1c239SDimitry Andric return e;
1188d2d3ebb8SDimitry Andric }
1189d2d3ebb8SDimitry Andric
combine(StringRef op,Expr l,Expr r)1190f1e1c239SDimitry Andric Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
1191f1e1c239SDimitry Andric if (op == "+")
1192f1e1c239SDimitry Andric return [=] { return add(l(), r()); };
1193f1e1c239SDimitry Andric if (op == "-")
1194f1e1c239SDimitry Andric return [=] { return sub(l(), r()); };
1195f1e1c239SDimitry Andric if (op == "*")
1196f1e1c239SDimitry Andric return [=] { return l().getValue() * r().getValue(); };
1197f1e1c239SDimitry Andric if (op == "/") {
1198f1e1c239SDimitry Andric std::string loc = getCurrentLocation();
119920d35e67SDimitry Andric return [=]() -> uint64_t {
1200f1e1c239SDimitry Andric if (uint64_t rv = r().getValue())
1201f1e1c239SDimitry Andric return l().getValue() / rv;
1202f1e1c239SDimitry Andric error(loc + ": division by zero");
120320d35e67SDimitry Andric return 0;
120420d35e67SDimitry Andric };
120520d35e67SDimitry Andric }
1206f1e1c239SDimitry Andric if (op == "%") {
1207f1e1c239SDimitry Andric std::string loc = getCurrentLocation();
120820d35e67SDimitry Andric return [=]() -> uint64_t {
1209f1e1c239SDimitry Andric if (uint64_t rv = r().getValue())
1210f1e1c239SDimitry Andric return l().getValue() % rv;
1211f1e1c239SDimitry Andric error(loc + ": modulo by zero");
121220d35e67SDimitry Andric return 0;
121320d35e67SDimitry Andric };
121420d35e67SDimitry Andric }
1215f1e1c239SDimitry Andric if (op == "<<")
12167fa27ce4SDimitry Andric return [=] { return l().getValue() << r().getValue() % 64; };
1217f1e1c239SDimitry Andric if (op == ">>")
12187fa27ce4SDimitry Andric return [=] { return l().getValue() >> r().getValue() % 64; };
1219f1e1c239SDimitry Andric if (op == "<")
1220f1e1c239SDimitry Andric return [=] { return l().getValue() < r().getValue(); };
1221f1e1c239SDimitry Andric if (op == ">")
1222f1e1c239SDimitry Andric return [=] { return l().getValue() > r().getValue(); };
1223f1e1c239SDimitry Andric if (op == ">=")
1224f1e1c239SDimitry Andric return [=] { return l().getValue() >= r().getValue(); };
1225f1e1c239SDimitry Andric if (op == "<=")
1226f1e1c239SDimitry Andric return [=] { return l().getValue() <= r().getValue(); };
1227f1e1c239SDimitry Andric if (op == "==")
1228f1e1c239SDimitry Andric return [=] { return l().getValue() == r().getValue(); };
1229f1e1c239SDimitry Andric if (op == "!=")
1230f1e1c239SDimitry Andric return [=] { return l().getValue() != r().getValue(); };
1231f1e1c239SDimitry Andric if (op == "||")
1232f1e1c239SDimitry Andric return [=] { return l().getValue() || r().getValue(); };
1233f1e1c239SDimitry Andric if (op == "&&")
1234f1e1c239SDimitry Andric return [=] { return l().getValue() && r().getValue(); };
1235f1e1c239SDimitry Andric if (op == "&")
1236f1e1c239SDimitry Andric return [=] { return bitAnd(l(), r()); };
12377fa27ce4SDimitry Andric if (op == "^")
12387fa27ce4SDimitry Andric return [=] { return bitXor(l(), r()); };
1239f1e1c239SDimitry Andric if (op == "|")
1240f1e1c239SDimitry Andric return [=] { return bitOr(l(), r()); };
1241d2d3ebb8SDimitry Andric llvm_unreachable("invalid operator");
1242d2d3ebb8SDimitry Andric }
1243d2d3ebb8SDimitry Andric
1244d2d3ebb8SDimitry Andric // This is a part of the operator-precedence parser. This function
1245d2d3ebb8SDimitry Andric // assumes that the remaining token stream starts with an operator.
readExpr1(Expr lhs,int minPrec)1246f1e1c239SDimitry Andric Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1247eb1ff93dSDimitry Andric while (!atEOF() && !errorCount()) {
1248d2d3ebb8SDimitry Andric // Read an operator and an expression.
1249f1e1c239SDimitry Andric StringRef op1 = peek();
1250f1e1c239SDimitry Andric if (precedence(op1) < minPrec)
1251d2d3ebb8SDimitry Andric break;
1252d2d3ebb8SDimitry Andric skip();
1253ac9a064cSDimitry Andric if (op1 == "?")
1254ac9a064cSDimitry Andric return readTernary(lhs);
1255f1e1c239SDimitry Andric Expr rhs = readPrimary();
1256d2d3ebb8SDimitry Andric
1257d2d3ebb8SDimitry Andric // Evaluate the remaining part of the expression first if the
1258d2d3ebb8SDimitry Andric // next operator has greater precedence than the previous one.
1259d2d3ebb8SDimitry Andric // For example, if we have read "+" and "3", and if the next
1260d2d3ebb8SDimitry Andric // operator is "*", then we'll evaluate 3 * ... part first.
1261d2d3ebb8SDimitry Andric while (!atEOF()) {
1262f1e1c239SDimitry Andric StringRef op2 = peek();
1263f1e1c239SDimitry Andric if (precedence(op2) <= precedence(op1))
1264d2d3ebb8SDimitry Andric break;
1265f1e1c239SDimitry Andric rhs = readExpr1(rhs, precedence(op2));
1266d2d3ebb8SDimitry Andric }
1267d2d3ebb8SDimitry Andric
1268f1e1c239SDimitry Andric lhs = combine(op1, lhs, rhs);
1269d2d3ebb8SDimitry Andric }
1270f1e1c239SDimitry Andric return lhs;
1271d2d3ebb8SDimitry Andric }
1272d2d3ebb8SDimitry Andric
getPageSize()1273eb1ff93dSDimitry Andric Expr ScriptParser::getPageSize() {
1274f1e1c239SDimitry Andric std::string location = getCurrentLocation();
1275eb1ff93dSDimitry Andric return [=]() -> uint64_t {
1276f1e1c239SDimitry Andric if (target)
1277f1e1c239SDimitry Andric return config->commonPageSize;
1278f1e1c239SDimitry Andric error(location + ": unable to calculate page size");
1279eb1ff93dSDimitry Andric return 4096; // Return a dummy value.
1280eb1ff93dSDimitry Andric };
1281eb1ff93dSDimitry Andric }
1282eb1ff93dSDimitry Andric
readConstant()1283eb1ff93dSDimitry Andric Expr ScriptParser::readConstant() {
1284f1e1c239SDimitry Andric StringRef s = readParenLiteral();
1285f1e1c239SDimitry Andric if (s == "COMMONPAGESIZE")
1286eb1ff93dSDimitry Andric return getPageSize();
1287f1e1c239SDimitry Andric if (s == "MAXPAGESIZE")
1288f1e1c239SDimitry Andric return [] { return config->maxPageSize; };
1289f1e1c239SDimitry Andric setError("unknown constant: " + s);
129020d35e67SDimitry Andric return [] { return 0; };
1291d2d3ebb8SDimitry Andric }
1292d2d3ebb8SDimitry Andric
1293d2d3ebb8SDimitry Andric // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1294d2d3ebb8SDimitry Andric // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1295d2d3ebb8SDimitry Andric // have "K" (Ki) or "M" (Mi) suffixes.
parseInt(StringRef tok)1296e3b55780SDimitry Andric static std::optional<uint64_t> parseInt(StringRef tok) {
1297d2d3ebb8SDimitry Andric // Hexadecimal
1298f1e1c239SDimitry Andric uint64_t val;
12997fa27ce4SDimitry Andric if (tok.starts_with_insensitive("0x")) {
1300f1e1c239SDimitry Andric if (!to_integer(tok.substr(2), val, 16))
1301e3b55780SDimitry Andric return std::nullopt;
1302f1e1c239SDimitry Andric return val;
1303eb1ff93dSDimitry Andric }
13047fa27ce4SDimitry Andric if (tok.ends_with_insensitive("H")) {
1305f1e1c239SDimitry Andric if (!to_integer(tok.drop_back(), val, 16))
1306e3b55780SDimitry Andric return std::nullopt;
1307f1e1c239SDimitry Andric return val;
1308eb1ff93dSDimitry Andric }
1309d2d3ebb8SDimitry Andric
1310d2d3ebb8SDimitry Andric // Decimal
13117fa27ce4SDimitry Andric if (tok.ends_with_insensitive("K")) {
1312f1e1c239SDimitry Andric if (!to_integer(tok.drop_back(), val, 10))
1313e3b55780SDimitry Andric return std::nullopt;
1314f1e1c239SDimitry Andric return val * 1024;
1315d2d3ebb8SDimitry Andric }
13167fa27ce4SDimitry Andric if (tok.ends_with_insensitive("M")) {
1317f1e1c239SDimitry Andric if (!to_integer(tok.drop_back(), val, 10))
1318e3b55780SDimitry Andric return std::nullopt;
1319f1e1c239SDimitry Andric return val * 1024 * 1024;
1320d2d3ebb8SDimitry Andric }
1321f1e1c239SDimitry Andric if (!to_integer(tok, val, 10))
1322e3b55780SDimitry Andric return std::nullopt;
1323f1e1c239SDimitry Andric return val;
1324d2d3ebb8SDimitry Andric }
1325d2d3ebb8SDimitry Andric
readByteCommand(StringRef tok)1326f1e1c239SDimitry Andric ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
1327f1e1c239SDimitry Andric int size = StringSwitch<int>(tok)
1328d2d3ebb8SDimitry Andric .Case("BYTE", 1)
1329d2d3ebb8SDimitry Andric .Case("SHORT", 2)
1330d2d3ebb8SDimitry Andric .Case("LONG", 4)
1331d2d3ebb8SDimitry Andric .Case("QUAD", 8)
1332d2d3ebb8SDimitry Andric .Default(-1);
1333f1e1c239SDimitry Andric if (size == -1)
1334d2d3ebb8SDimitry Andric return nullptr;
133520d35e67SDimitry Andric
1336f1e1c239SDimitry Andric size_t oldPos = pos;
1337f1e1c239SDimitry Andric Expr e = readParenExpr();
1338f1e1c239SDimitry Andric std::string commandString =
1339f1e1c239SDimitry Andric tok.str() + " " +
1340f1e1c239SDimitry Andric llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1341f1e1c239SDimitry Andric return make<ByteCommand>(e, size, commandString);
1342d2d3ebb8SDimitry Andric }
1343d2d3ebb8SDimitry Andric
parseFlag(StringRef tok)1344e3b55780SDimitry Andric static std::optional<uint64_t> parseFlag(StringRef tok) {
1345e3b55780SDimitry Andric if (std::optional<uint64_t> asInt = parseInt(tok))
1346cfca06d7SDimitry Andric return asInt;
1347cfca06d7SDimitry Andric #define CASE_ENT(enum) #enum, ELF::enum
1348e3b55780SDimitry Andric return StringSwitch<std::optional<uint64_t>>(tok)
1349cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_WRITE))
1350cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_ALLOC))
1351cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_EXECINSTR))
1352cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_MERGE))
1353cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_STRINGS))
1354cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_INFO_LINK))
1355cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_LINK_ORDER))
1356cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1357cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_GROUP))
1358cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_TLS))
1359cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_COMPRESSED))
1360cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_EXCLUDE))
1361cfca06d7SDimitry Andric .Case(CASE_ENT(SHF_ARM_PURECODE))
1362e3b55780SDimitry Andric .Default(std::nullopt);
1363cfca06d7SDimitry Andric #undef CASE_ENT
1364cfca06d7SDimitry Andric }
1365cfca06d7SDimitry Andric
1366cfca06d7SDimitry Andric // Reads the '(' <flags> ')' list of section flags in
1367cfca06d7SDimitry Andric // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1368cfca06d7SDimitry Andric // following form:
1369cfca06d7SDimitry Andric // <flags> ::= <flag>
1370cfca06d7SDimitry Andric // | <flags> & flag
1371cfca06d7SDimitry Andric // <flag> ::= Recognized Flag Name, or Integer value of flag.
1372cfca06d7SDimitry Andric // If the first character of <flag> is a ! then this means without flag,
1373cfca06d7SDimitry Andric // otherwise with flag.
1374cfca06d7SDimitry Andric // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1375cfca06d7SDimitry Andric // without flag SHF_WRITE.
readInputSectionFlags()1376cfca06d7SDimitry Andric std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1377cfca06d7SDimitry Andric uint64_t withFlags = 0;
1378cfca06d7SDimitry Andric uint64_t withoutFlags = 0;
1379cfca06d7SDimitry Andric expect("(");
1380cfca06d7SDimitry Andric while (!errorCount()) {
1381cfca06d7SDimitry Andric StringRef tok = unquote(next());
1382cfca06d7SDimitry Andric bool without = tok.consume_front("!");
1383e3b55780SDimitry Andric if (std::optional<uint64_t> flag = parseFlag(tok)) {
1384cfca06d7SDimitry Andric if (without)
1385cfca06d7SDimitry Andric withoutFlags |= *flag;
1386cfca06d7SDimitry Andric else
1387cfca06d7SDimitry Andric withFlags |= *flag;
1388cfca06d7SDimitry Andric } else {
1389cfca06d7SDimitry Andric setError("unrecognised flag: " + tok);
1390cfca06d7SDimitry Andric }
1391cfca06d7SDimitry Andric if (consume(")"))
1392cfca06d7SDimitry Andric break;
1393cfca06d7SDimitry Andric if (!consume("&")) {
1394cfca06d7SDimitry Andric next();
1395cfca06d7SDimitry Andric setError("expected & or )");
1396cfca06d7SDimitry Andric }
1397cfca06d7SDimitry Andric }
1398cfca06d7SDimitry Andric return std::make_pair(withFlags, withoutFlags);
1399cfca06d7SDimitry Andric }
1400cfca06d7SDimitry Andric
readParenLiteral()1401d2d3ebb8SDimitry Andric StringRef ScriptParser::readParenLiteral() {
1402d2d3ebb8SDimitry Andric expect("(");
1403f1e1c239SDimitry Andric bool orig = inExpr;
1404f1e1c239SDimitry Andric inExpr = false;
1405f1e1c239SDimitry Andric StringRef tok = next();
1406f1e1c239SDimitry Andric inExpr = orig;
1407d2d3ebb8SDimitry Andric expect(")");
1408f1e1c239SDimitry Andric return tok;
1409d2d3ebb8SDimitry Andric }
1410d2d3ebb8SDimitry Andric
checkIfExists(const OutputSection & osec,StringRef location)1411145449b1SDimitry Andric static void checkIfExists(const OutputSection &osec, StringRef location) {
1412145449b1SDimitry Andric if (osec.location.empty() && script->errorOnMissingSection)
1413ac9a064cSDimitry Andric script->recordError(location + ": undefined section " + osec.name);
141480350c11SDimitry Andric }
141580350c11SDimitry Andric
isValidSymbolName(StringRef s)1416344a3780SDimitry Andric static bool isValidSymbolName(StringRef s) {
1417344a3780SDimitry Andric auto valid = [](char c) {
1418344a3780SDimitry Andric return isAlnum(c) || c == '$' || c == '.' || c == '_';
1419344a3780SDimitry Andric };
1420344a3780SDimitry Andric return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1421344a3780SDimitry Andric }
1422344a3780SDimitry Andric
readPrimary()1423d2d3ebb8SDimitry Andric Expr ScriptParser::readPrimary() {
1424d2d3ebb8SDimitry Andric if (peek() == "(")
1425d2d3ebb8SDimitry Andric return readParenExpr();
1426d2d3ebb8SDimitry Andric
1427d2d3ebb8SDimitry Andric if (consume("~")) {
1428f1e1c239SDimitry Andric Expr e = readPrimary();
1429f1e1c239SDimitry Andric return [=] { return ~e().getValue(); };
1430d2d3ebb8SDimitry Andric }
1431eb1ff93dSDimitry Andric if (consume("!")) {
1432f1e1c239SDimitry Andric Expr e = readPrimary();
1433f1e1c239SDimitry Andric return [=] { return !e().getValue(); };
1434eb1ff93dSDimitry Andric }
1435d2d3ebb8SDimitry Andric if (consume("-")) {
1436f1e1c239SDimitry Andric Expr e = readPrimary();
1437f1e1c239SDimitry Andric return [=] { return -e().getValue(); };
1438d2d3ebb8SDimitry Andric }
1439d2d3ebb8SDimitry Andric
1440f1e1c239SDimitry Andric StringRef tok = next();
1441f1e1c239SDimitry Andric std::string location = getCurrentLocation();
1442d2d3ebb8SDimitry Andric
1443d2d3ebb8SDimitry Andric // Built-in functions are parsed here.
1444d2d3ebb8SDimitry Andric // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1445f1e1c239SDimitry Andric if (tok == "ABSOLUTE") {
1446f1e1c239SDimitry Andric Expr inner = readParenExpr();
1447d2d3ebb8SDimitry Andric return [=] {
1448f1e1c239SDimitry Andric ExprValue i = inner();
1449f1e1c239SDimitry Andric i.forceAbsolute = true;
1450f1e1c239SDimitry Andric return i;
1451d2d3ebb8SDimitry Andric };
1452d2d3ebb8SDimitry Andric }
1453f1e1c239SDimitry Andric if (tok == "ADDR") {
14547fa27ce4SDimitry Andric StringRef name = unquote(readParenLiteral());
1455145449b1SDimitry Andric OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1456145449b1SDimitry Andric osec->usedInExpression = true;
14572079716dSDimitry Andric return [=]() -> ExprValue {
1458145449b1SDimitry Andric checkIfExists(*osec, location);
1459145449b1SDimitry Andric return {osec, false, 0, location};
14602079716dSDimitry Andric };
1461d2d3ebb8SDimitry Andric }
1462f1e1c239SDimitry Andric if (tok == "ALIGN") {
1463d2d3ebb8SDimitry Andric expect("(");
1464f1e1c239SDimitry Andric Expr e = readExpr();
1465eb1ff93dSDimitry Andric if (consume(")")) {
1466f1e1c239SDimitry Andric e = checkAlignment(e, location);
146708e8dd7bSDimitry Andric return [=] { return alignToPowerOf2(script->getDot(), e().getValue()); };
1468eb1ff93dSDimitry Andric }
1469d2d3ebb8SDimitry Andric expect(",");
1470f1e1c239SDimitry Andric Expr e2 = checkAlignment(readExpr(), location);
1471d2d3ebb8SDimitry Andric expect(")");
1472cbb560c9SDimitry Andric return [=] {
1473f1e1c239SDimitry Andric ExprValue v = e();
1474f1e1c239SDimitry Andric v.alignment = e2().getValue();
1475f1e1c239SDimitry Andric return v;
1476cbb560c9SDimitry Andric };
1477d2d3ebb8SDimitry Andric }
1478f1e1c239SDimitry Andric if (tok == "ALIGNOF") {
14797fa27ce4SDimitry Andric StringRef name = unquote(readParenLiteral());
1480145449b1SDimitry Andric OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1481eb1ff93dSDimitry Andric return [=] {
1482145449b1SDimitry Andric checkIfExists(*osec, location);
1483e3b55780SDimitry Andric return osec->addralign;
1484eb1ff93dSDimitry Andric };
1485d2d3ebb8SDimitry Andric }
1486f1e1c239SDimitry Andric if (tok == "ASSERT")
148720d35e67SDimitry Andric return readAssert();
1488f1e1c239SDimitry Andric if (tok == "CONSTANT")
1489eb1ff93dSDimitry Andric return readConstant();
1490f1e1c239SDimitry Andric if (tok == "DATA_SEGMENT_ALIGN") {
1491d2d3ebb8SDimitry Andric expect("(");
1492f1e1c239SDimitry Andric Expr e = readExpr();
1493d2d3ebb8SDimitry Andric expect(",");
1494d2d3ebb8SDimitry Andric readExpr();
1495d2d3ebb8SDimitry Andric expect(")");
1496b1c73532SDimitry Andric script->seenDataAlign = true;
1497eb1ff93dSDimitry Andric return [=] {
149808e8dd7bSDimitry Andric uint64_t align = std::max(uint64_t(1), e().getValue());
149908e8dd7bSDimitry Andric return (script->getDot() + align - 1) & -align;
1500eb1ff93dSDimitry Andric };
1501d2d3ebb8SDimitry Andric }
1502f1e1c239SDimitry Andric if (tok == "DATA_SEGMENT_END") {
1503d2d3ebb8SDimitry Andric expect("(");
1504d2d3ebb8SDimitry Andric expect(".");
1505d2d3ebb8SDimitry Andric expect(")");
1506f1e1c239SDimitry Andric return [] { return script->getDot(); };
1507d2d3ebb8SDimitry Andric }
1508f1e1c239SDimitry Andric if (tok == "DATA_SEGMENT_RELRO_END") {
1509d2d3ebb8SDimitry Andric // GNU linkers implements more complicated logic to handle
1510d2d3ebb8SDimitry Andric // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1511d2d3ebb8SDimitry Andric // just align to the next page boundary for simplicity.
1512d2d3ebb8SDimitry Andric expect("(");
1513d2d3ebb8SDimitry Andric readExpr();
1514d2d3ebb8SDimitry Andric expect(",");
1515d2d3ebb8SDimitry Andric readExpr();
1516d2d3ebb8SDimitry Andric expect(")");
1517b1c73532SDimitry Andric script->seenRelroEnd = true;
1518b1c73532SDimitry Andric return [=] { return alignToPowerOf2(script->getDot(), config->maxPageSize); };
1519d2d3ebb8SDimitry Andric }
1520f1e1c239SDimitry Andric if (tok == "DEFINED") {
1521344a3780SDimitry Andric StringRef name = unquote(readParenLiteral());
1522b1c73532SDimitry Andric // Return 1 if s is defined. If the definition is only found in a linker
1523b1c73532SDimitry Andric // script, it must happen before this DEFINED.
1524b1c73532SDimitry Andric auto order = ctx.scriptSymOrderCounter++;
1525b60736ecSDimitry Andric return [=] {
1526b1c73532SDimitry Andric Symbol *s = symtab.find(name);
1527b1c73532SDimitry Andric return s && s->isDefined() && ctx.scriptSymOrder.lookup(s) < order ? 1
1528b1c73532SDimitry Andric : 0;
1529b60736ecSDimitry Andric };
1530d2d3ebb8SDimitry Andric }
1531f1e1c239SDimitry Andric if (tok == "LENGTH") {
1532f1e1c239SDimitry Andric StringRef name = readParenLiteral();
1533f1e1c239SDimitry Andric if (script->memoryRegions.count(name) == 0) {
1534f1e1c239SDimitry Andric setError("memory region not defined: " + name);
153520d35e67SDimitry Andric return [] { return 0; };
153620d35e67SDimitry Andric }
1537cfca06d7SDimitry Andric return script->memoryRegions[name]->length;
1538022ebf5bSDimitry Andric }
1539f1e1c239SDimitry Andric if (tok == "LOADADDR") {
15407fa27ce4SDimitry Andric StringRef name = unquote(readParenLiteral());
1541145449b1SDimitry Andric OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1542145449b1SDimitry Andric osec->usedInExpression = true;
1543eb1ff93dSDimitry Andric return [=] {
1544145449b1SDimitry Andric checkIfExists(*osec, location);
1545145449b1SDimitry Andric return osec->getLMA();
1546eb1ff93dSDimitry Andric };
1547d2d3ebb8SDimitry Andric }
1548b60736ecSDimitry Andric if (tok == "LOG2CEIL") {
1549b60736ecSDimitry Andric expect("(");
1550b60736ecSDimitry Andric Expr a = readExpr();
1551b60736ecSDimitry Andric expect(")");
1552b60736ecSDimitry Andric return [=] {
1553b60736ecSDimitry Andric // LOG2CEIL(0) is defined to be 0.
1554b60736ecSDimitry Andric return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1555b60736ecSDimitry Andric };
1556b60736ecSDimitry Andric }
1557f1e1c239SDimitry Andric if (tok == "MAX" || tok == "MIN") {
155820d35e67SDimitry Andric expect("(");
1559f1e1c239SDimitry Andric Expr a = readExpr();
156020d35e67SDimitry Andric expect(",");
1561f1e1c239SDimitry Andric Expr b = readExpr();
156220d35e67SDimitry Andric expect(")");
1563f1e1c239SDimitry Andric if (tok == "MIN")
1564f1e1c239SDimitry Andric return [=] { return std::min(a().getValue(), b().getValue()); };
1565f1e1c239SDimitry Andric return [=] { return std::max(a().getValue(), b().getValue()); };
156620d35e67SDimitry Andric }
1567f1e1c239SDimitry Andric if (tok == "ORIGIN") {
1568f1e1c239SDimitry Andric StringRef name = readParenLiteral();
1569f1e1c239SDimitry Andric if (script->memoryRegions.count(name) == 0) {
1570f1e1c239SDimitry Andric setError("memory region not defined: " + name);
157120d35e67SDimitry Andric return [] { return 0; };
157220d35e67SDimitry Andric }
1573cfca06d7SDimitry Andric return script->memoryRegions[name]->origin;
1574022ebf5bSDimitry Andric }
1575f1e1c239SDimitry Andric if (tok == "SEGMENT_START") {
1576d2d3ebb8SDimitry Andric expect("(");
1577d2d3ebb8SDimitry Andric skip();
1578d2d3ebb8SDimitry Andric expect(",");
1579f1e1c239SDimitry Andric Expr e = readExpr();
1580d2d3ebb8SDimitry Andric expect(")");
1581f1e1c239SDimitry Andric return [=] { return e(); };
1582d2d3ebb8SDimitry Andric }
1583f1e1c239SDimitry Andric if (tok == "SIZEOF") {
15847fa27ce4SDimitry Andric StringRef name = unquote(readParenLiteral());
1585145449b1SDimitry Andric OutputSection *cmd = &script->getOrCreateOutputSection(name)->osec;
158680350c11SDimitry Andric // Linker script does not create an output section if its content is empty.
158780350c11SDimitry Andric // We want to allow SIZEOF(.foo) where .foo is a section which happened to
158880350c11SDimitry Andric // be empty.
1589f1e1c239SDimitry Andric return [=] { return cmd->size; };
1590d2d3ebb8SDimitry Andric }
1591f1e1c239SDimitry Andric if (tok == "SIZEOF_HEADERS")
1592cfca06d7SDimitry Andric return [=] { return elf::getHeaderSize(); };
1593d2d3ebb8SDimitry Andric
1594d2d3ebb8SDimitry Andric // Tok is the dot.
1595f1e1c239SDimitry Andric if (tok == ".")
1596f1e1c239SDimitry Andric return [=] { return script->getSymbolValue(tok, location); };
1597d2d3ebb8SDimitry Andric
1598d2d3ebb8SDimitry Andric // Tok is a literal number.
1599e3b55780SDimitry Andric if (std::optional<uint64_t> val = parseInt(tok))
1600f1e1c239SDimitry Andric return [=] { return *val; };
1601d2d3ebb8SDimitry Andric
1602d2d3ebb8SDimitry Andric // Tok is a symbol name.
16037fa27ce4SDimitry Andric if (tok.starts_with("\""))
1604344a3780SDimitry Andric tok = unquote(tok);
1605c0981da4SDimitry Andric else if (!isValidSymbolName(tok))
1606f1e1c239SDimitry Andric setError("malformed number: " + tok);
1607ac9a064cSDimitry Andric if (activeProvideSym)
1608ac9a064cSDimitry Andric script->provideMap[*activeProvideSym].push_back(tok);
1609ac9a064cSDimitry Andric else
1610f1e1c239SDimitry Andric script->referencedSymbols.push_back(tok);
1611f1e1c239SDimitry Andric return [=] { return script->getSymbolValue(tok, location); };
1612d2d3ebb8SDimitry Andric }
1613d2d3ebb8SDimitry Andric
readTernary(Expr cond)1614f1e1c239SDimitry Andric Expr ScriptParser::readTernary(Expr cond) {
1615f1e1c239SDimitry Andric Expr l = readExpr();
1616d2d3ebb8SDimitry Andric expect(":");
1617f1e1c239SDimitry Andric Expr r = readExpr();
1618f1e1c239SDimitry Andric return [=] { return cond().getValue() ? l() : r(); };
1619d2d3ebb8SDimitry Andric }
1620d2d3ebb8SDimitry Andric
readParenExpr()1621d2d3ebb8SDimitry Andric Expr ScriptParser::readParenExpr() {
1622d2d3ebb8SDimitry Andric expect("(");
1623f1e1c239SDimitry Andric Expr e = readExpr();
1624d2d3ebb8SDimitry Andric expect(")");
1625f1e1c239SDimitry Andric return e;
1626d2d3ebb8SDimitry Andric }
1627d2d3ebb8SDimitry Andric
readOutputSectionPhdrs()16286f8fc217SDimitry Andric SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {
16296f8fc217SDimitry Andric SmallVector<StringRef, 0> phdrs;
16307fa27ce4SDimitry Andric while (!errorCount() && peek().starts_with(":")) {
1631f1e1c239SDimitry Andric StringRef tok = next();
1632f1e1c239SDimitry Andric phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
1633d2d3ebb8SDimitry Andric }
1634f1e1c239SDimitry Andric return phdrs;
1635d2d3ebb8SDimitry Andric }
1636d2d3ebb8SDimitry Andric
1637d2d3ebb8SDimitry Andric // Read a program header type name. The next token must be a
1638d2d3ebb8SDimitry Andric // name of a program header type or a constant (e.g. "0x3").
readPhdrType()1639d2d3ebb8SDimitry Andric unsigned ScriptParser::readPhdrType() {
1640f1e1c239SDimitry Andric StringRef tok = next();
1641e3b55780SDimitry Andric if (std::optional<uint64_t> val = parseInt(tok))
1642f1e1c239SDimitry Andric return *val;
1643d2d3ebb8SDimitry Andric
1644f1e1c239SDimitry Andric unsigned ret = StringSwitch<unsigned>(tok)
1645d2d3ebb8SDimitry Andric .Case("PT_NULL", PT_NULL)
1646d2d3ebb8SDimitry Andric .Case("PT_LOAD", PT_LOAD)
1647d2d3ebb8SDimitry Andric .Case("PT_DYNAMIC", PT_DYNAMIC)
1648d2d3ebb8SDimitry Andric .Case("PT_INTERP", PT_INTERP)
1649d2d3ebb8SDimitry Andric .Case("PT_NOTE", PT_NOTE)
1650d2d3ebb8SDimitry Andric .Case("PT_SHLIB", PT_SHLIB)
1651d2d3ebb8SDimitry Andric .Case("PT_PHDR", PT_PHDR)
1652d2d3ebb8SDimitry Andric .Case("PT_TLS", PT_TLS)
1653d2d3ebb8SDimitry Andric .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1654d2d3ebb8SDimitry Andric .Case("PT_GNU_STACK", PT_GNU_STACK)
1655d2d3ebb8SDimitry Andric .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1656ac9a064cSDimitry Andric .Case("PT_OPENBSD_MUTABLE", PT_OPENBSD_MUTABLE)
1657d2d3ebb8SDimitry Andric .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1658ac9a064cSDimitry Andric .Case("PT_OPENBSD_SYSCALLS", PT_OPENBSD_SYSCALLS)
1659d2d3ebb8SDimitry Andric .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1660d2d3ebb8SDimitry Andric .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1661d2d3ebb8SDimitry Andric .Default(-1);
1662d2d3ebb8SDimitry Andric
1663f1e1c239SDimitry Andric if (ret == (unsigned)-1) {
1664f1e1c239SDimitry Andric setError("invalid program header type: " + tok);
1665d2d3ebb8SDimitry Andric return PT_NULL;
1666d2d3ebb8SDimitry Andric }
1667f1e1c239SDimitry Andric return ret;
1668d2d3ebb8SDimitry Andric }
1669d2d3ebb8SDimitry Andric
1670d2d3ebb8SDimitry Andric // Reads an anonymous version declaration.
readAnonymousDeclaration()1671d2d3ebb8SDimitry Andric void ScriptParser::readAnonymousDeclaration() {
16726f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> locals;
16736f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> globals;
1674f1e1c239SDimitry Andric std::tie(locals, globals) = readSymbols();
1675d2bd9e70SDimitry Andric for (const SymbolVersion &pat : locals)
1676c0981da4SDimitry Andric config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat);
1677d2bd9e70SDimitry Andric for (const SymbolVersion &pat : globals)
1678c0981da4SDimitry Andric config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat);
1679d2d3ebb8SDimitry Andric
1680d2d3ebb8SDimitry Andric expect(";");
1681d2d3ebb8SDimitry Andric }
1682d2d3ebb8SDimitry Andric
1683d2d3ebb8SDimitry Andric // Reads a non-anonymous version definition,
1684d2d3ebb8SDimitry Andric // e.g. "VerStr { global: foo; bar; local: *; };".
readVersionDeclaration(StringRef verStr)1685f1e1c239SDimitry Andric void ScriptParser::readVersionDeclaration(StringRef verStr) {
1686d2d3ebb8SDimitry Andric // Read a symbol list.
16876f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> locals;
16886f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> globals;
1689f1e1c239SDimitry Andric std::tie(locals, globals) = readSymbols();
1690d2d3ebb8SDimitry Andric
1691d2d3ebb8SDimitry Andric // Create a new version definition and add that to the global symbols.
1692f1e1c239SDimitry Andric VersionDefinition ver;
1693f1e1c239SDimitry Andric ver.name = verStr;
1694c0981da4SDimitry Andric ver.nonLocalPatterns = std::move(globals);
1695c0981da4SDimitry Andric ver.localPatterns = std::move(locals);
1696d2bd9e70SDimitry Andric ver.id = config->versionDefinitions.size();
1697f1e1c239SDimitry Andric config->versionDefinitions.push_back(ver);
1698d2d3ebb8SDimitry Andric
1699d2d3ebb8SDimitry Andric // Each version may have a parent version. For example, "Ver2"
1700d2d3ebb8SDimitry Andric // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1701d2d3ebb8SDimitry Andric // as a parent. This version hierarchy is, probably against your
1702d2d3ebb8SDimitry Andric // instinct, purely for hint; the runtime doesn't care about it
1703d2d3ebb8SDimitry Andric // at all. In LLD, we simply ignore it.
1704cfca06d7SDimitry Andric if (next() != ";")
1705d2d3ebb8SDimitry Andric expect(";");
1706d2d3ebb8SDimitry Andric }
1707d2d3ebb8SDimitry Andric
hasWildcard(StringRef s)1708cfca06d7SDimitry Andric bool elf::hasWildcard(StringRef s) {
1709f1e1c239SDimitry Andric return s.find_first_of("?*[") != StringRef::npos;
1710da06c7cfSDimitry Andric }
1711da06c7cfSDimitry Andric
1712d2d3ebb8SDimitry Andric // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
17136f8fc217SDimitry Andric std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
readSymbols()1714d2d3ebb8SDimitry Andric ScriptParser::readSymbols() {
17156f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> locals;
17166f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> globals;
17176f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> *v = &globals;
1718d2d3ebb8SDimitry Andric
1719eb1ff93dSDimitry Andric while (!errorCount()) {
1720d2d3ebb8SDimitry Andric if (consume("}"))
1721d2d3ebb8SDimitry Andric break;
1722d2d3ebb8SDimitry Andric if (consumeLabel("local")) {
1723f1e1c239SDimitry Andric v = &locals;
1724d2d3ebb8SDimitry Andric continue;
1725d2d3ebb8SDimitry Andric }
1726d2d3ebb8SDimitry Andric if (consumeLabel("global")) {
1727f1e1c239SDimitry Andric v = &globals;
1728d2d3ebb8SDimitry Andric continue;
1729d2d3ebb8SDimitry Andric }
1730d2d3ebb8SDimitry Andric
1731d2d3ebb8SDimitry Andric if (consume("extern")) {
17326f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> ext = readVersionExtern();
1733f1e1c239SDimitry Andric v->insert(v->end(), ext.begin(), ext.end());
1734d2d3ebb8SDimitry Andric } else {
1735f1e1c239SDimitry Andric StringRef tok = next();
1736f1e1c239SDimitry Andric v->push_back({unquote(tok), false, hasWildcard(tok)});
1737d2d3ebb8SDimitry Andric }
1738d2d3ebb8SDimitry Andric expect(";");
1739d2d3ebb8SDimitry Andric }
1740f1e1c239SDimitry Andric return {locals, globals};
1741d2d3ebb8SDimitry Andric }
1742d2d3ebb8SDimitry Andric
1743d2d3ebb8SDimitry Andric // Reads an "extern C++" directive, e.g.,
1744d2d3ebb8SDimitry Andric // "extern "C++" { ns::*; "f(int, double)"; };"
174520d35e67SDimitry Andric //
174620d35e67SDimitry Andric // The last semicolon is optional. E.g. this is OK:
174720d35e67SDimitry Andric // "extern "C++" { ns::*; "f(int, double)" };"
readVersionExtern()17486f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {
1749f1e1c239SDimitry Andric StringRef tok = next();
1750f1e1c239SDimitry Andric bool isCXX = tok == "\"C++\"";
1751f1e1c239SDimitry Andric if (!isCXX && tok != "\"C\"")
1752d2d3ebb8SDimitry Andric setError("Unknown language");
1753d2d3ebb8SDimitry Andric expect("{");
1754d2d3ebb8SDimitry Andric
17556f8fc217SDimitry Andric SmallVector<SymbolVersion, 0> ret;
1756eb1ff93dSDimitry Andric while (!errorCount() && peek() != "}") {
1757f1e1c239SDimitry Andric StringRef tok = next();
1758f1e1c239SDimitry Andric ret.push_back(
17597fa27ce4SDimitry Andric {unquote(tok), isCXX, !tok.starts_with("\"") && hasWildcard(tok)});
176020d35e67SDimitry Andric if (consume("}"))
1761f1e1c239SDimitry Andric return ret;
1762d2d3ebb8SDimitry Andric expect(";");
1763d2d3ebb8SDimitry Andric }
1764d2d3ebb8SDimitry Andric
1765d2d3ebb8SDimitry Andric expect("}");
1766f1e1c239SDimitry Andric return ret;
1767d2d3ebb8SDimitry Andric }
1768d2d3ebb8SDimitry Andric
readMemoryAssignment(StringRef s1,StringRef s2,StringRef s3)1769cfca06d7SDimitry Andric Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
1770f1e1c239SDimitry Andric StringRef s3) {
1771f1e1c239SDimitry Andric if (!consume(s1) && !consume(s2) && !consume(s3)) {
1772f1e1c239SDimitry Andric setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
1773cfca06d7SDimitry Andric return [] { return 0; };
1774d2d3ebb8SDimitry Andric }
1775d2d3ebb8SDimitry Andric expect("=");
1776cfca06d7SDimitry Andric return readExpr();
1777d2d3ebb8SDimitry Andric }
1778d2d3ebb8SDimitry Andric
1779d2d3ebb8SDimitry Andric // Parse the MEMORY command as specified in:
1780d2d3ebb8SDimitry Andric // https://sourceware.org/binutils/docs/ld/MEMORY.html
1781d2d3ebb8SDimitry Andric //
1782d2d3ebb8SDimitry Andric // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
readMemory()1783d2d3ebb8SDimitry Andric void ScriptParser::readMemory() {
1784d2d3ebb8SDimitry Andric expect("{");
1785eb1ff93dSDimitry Andric while (!errorCount() && !consume("}")) {
1786f1e1c239SDimitry Andric StringRef tok = next();
1787f1e1c239SDimitry Andric if (tok == "INCLUDE") {
1788e2fd426bSDimitry Andric readInclude();
1789e2fd426bSDimitry Andric continue;
1790e2fd426bSDimitry Andric }
1791d2d3ebb8SDimitry Andric
1792f1e1c239SDimitry Andric uint32_t flags = 0;
1793f65dcba8SDimitry Andric uint32_t invFlags = 0;
1794f1e1c239SDimitry Andric uint32_t negFlags = 0;
1795f65dcba8SDimitry Andric uint32_t negInvFlags = 0;
1796d2d3ebb8SDimitry Andric if (consume("(")) {
1797f65dcba8SDimitry Andric readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);
1798d2d3ebb8SDimitry Andric expect(")");
1799d2d3ebb8SDimitry Andric }
1800d2d3ebb8SDimitry Andric expect(":");
1801d2d3ebb8SDimitry Andric
1802cfca06d7SDimitry Andric Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
1803d2d3ebb8SDimitry Andric expect(",");
1804cfca06d7SDimitry Andric Expr length = readMemoryAssignment("LENGTH", "len", "l");
1805d2d3ebb8SDimitry Andric
1806eb1ff93dSDimitry Andric // Add the memory region to the region map.
1807f65dcba8SDimitry Andric MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags,
1808f65dcba8SDimitry Andric negFlags, negInvFlags);
1809f1e1c239SDimitry Andric if (!script->memoryRegions.insert({tok, mr}).second)
1810f1e1c239SDimitry Andric setError("region '" + tok + "' already defined");
1811d2d3ebb8SDimitry Andric }
1812d2d3ebb8SDimitry Andric }
1813d2d3ebb8SDimitry Andric
1814d2d3ebb8SDimitry Andric // This function parses the attributes used to match against section
1815d2d3ebb8SDimitry Andric // flags when placing output sections in a memory region. These flags
1816d2d3ebb8SDimitry Andric // are only used when an explicit memory region name is not used.
readMemoryAttributes(uint32_t & flags,uint32_t & invFlags,uint32_t & negFlags,uint32_t & negInvFlags)1817f65dcba8SDimitry Andric void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
1818f65dcba8SDimitry Andric uint32_t &negFlags,
1819f65dcba8SDimitry Andric uint32_t &negInvFlags) {
1820f1e1c239SDimitry Andric bool invert = false;
1821d2d3ebb8SDimitry Andric
1822f1e1c239SDimitry Andric for (char c : next().lower()) {
1823f65dcba8SDimitry Andric if (c == '!') {
1824f1e1c239SDimitry Andric invert = !invert;
1825f65dcba8SDimitry Andric std::swap(flags, negFlags);
1826f65dcba8SDimitry Andric std::swap(invFlags, negInvFlags);
1827f65dcba8SDimitry Andric continue;
1828d2d3ebb8SDimitry Andric }
1829f65dcba8SDimitry Andric if (c == 'w')
1830f65dcba8SDimitry Andric flags |= SHF_WRITE;
1831f65dcba8SDimitry Andric else if (c == 'x')
1832f65dcba8SDimitry Andric flags |= SHF_EXECINSTR;
1833f65dcba8SDimitry Andric else if (c == 'a')
1834f65dcba8SDimitry Andric flags |= SHF_ALLOC;
1835f65dcba8SDimitry Andric else if (c == 'r')
1836f65dcba8SDimitry Andric invFlags |= SHF_WRITE;
1837f65dcba8SDimitry Andric else
1838f65dcba8SDimitry Andric setError("invalid memory region attribute");
1839f65dcba8SDimitry Andric }
1840f65dcba8SDimitry Andric
1841f65dcba8SDimitry Andric if (invert) {
1842f65dcba8SDimitry Andric std::swap(flags, negFlags);
1843f65dcba8SDimitry Andric std::swap(invFlags, negInvFlags);
1844f65dcba8SDimitry Andric }
1845d2d3ebb8SDimitry Andric }
1846d2d3ebb8SDimitry Andric
readLinkerScript(MemoryBufferRef mb)1847cfca06d7SDimitry Andric void elf::readLinkerScript(MemoryBufferRef mb) {
1848b60736ecSDimitry Andric llvm::TimeTraceScope timeScope("Read linker script",
1849b60736ecSDimitry Andric mb.getBufferIdentifier());
1850f1e1c239SDimitry Andric ScriptParser(mb).readLinkerScript();
1851d2d3ebb8SDimitry Andric }
1852d2d3ebb8SDimitry Andric
readVersionScript(MemoryBufferRef mb)1853cfca06d7SDimitry Andric void elf::readVersionScript(MemoryBufferRef mb) {
1854b60736ecSDimitry Andric llvm::TimeTraceScope timeScope("Read version script",
1855b60736ecSDimitry Andric mb.getBufferIdentifier());
1856f1e1c239SDimitry Andric ScriptParser(mb).readVersionScript();
1857d2d3ebb8SDimitry Andric }
1858d2d3ebb8SDimitry Andric
readDynamicList(MemoryBufferRef mb)1859cfca06d7SDimitry Andric void elf::readDynamicList(MemoryBufferRef mb) {
1860b60736ecSDimitry Andric llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
1861cfca06d7SDimitry Andric ScriptParser(mb).readDynamicList();
1862eb1ff93dSDimitry Andric }
1863d2bd9e70SDimitry Andric
readDefsym(StringRef name,MemoryBufferRef mb)1864cfca06d7SDimitry Andric void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1865b60736ecSDimitry Andric llvm::TimeTraceScope timeScope("Read defsym input", name);
1866cfca06d7SDimitry Andric ScriptParser(mb).readDefsym(name);
1867cfca06d7SDimitry Andric }
1868