1//===- ScriptParser.cpp ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a recursive-descendent parser for linker scripts.
10// Parsed results are stored to Config and Script global objects.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ScriptParser.h"
15#include "Config.h"
16#include "Driver.h"
17#include "InputFiles.h"
18#include "LinkerScript.h"
19#include "OutputSections.h"
20#include "ScriptLexer.h"
21#include "SymbolTable.h"
22#include "Symbols.h"
23#include "Target.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/BinaryFormat/ELF.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/FileSystem.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/SaveAndRestore.h"
34#include "llvm/Support/TimeProfiler.h"
35#include <cassert>
36#include <optional>
37#include <vector>
38
39using namespace llvm;
40using namespace llvm::ELF;
41using namespace llvm::support::endian;
42using namespace lld;
43using namespace lld::elf;
44
45namespace {
46class ScriptParser final : ScriptLexer {
47public:
48 ScriptParser(Ctx &ctx, MemoryBufferRef mb) : ScriptLexer(ctx, mb), ctx(ctx) {}
49
50 void readLinkerScript();
51 void readVersionScript();
52 void readDynamicList();
53 void readDefsym();
54
55private:
56 void addFile(StringRef path);
57
58 void readAsNeeded();
59 void readEntry();
60 void readExtern();
61 void readGroup();
62 void readInclude();
63 void readInput();
64 void readMemory();
65 void readOutput();
66 void readOutputArch();
67 void readOutputFormat();
68 void readOverwriteSections();
69 void readPhdrs();
70 void readRegionAlias();
71 void readSearchDir();
72 void readSections();
73 void readTarget();
74 void readVersion();
75 void readVersionScriptCommand();
76 void readNoCrossRefs(bool to);
77
78 StringRef readName();
79 SymbolAssignment *readSymbolAssignment(StringRef name);
80 ByteCommand *readByteCommand(StringRef tok);
81 std::array<uint8_t, 4> readFill();
82 bool readSectionDirective(OutputSection *cmd, StringRef tok);
83 void readSectionAddressType(OutputSection *cmd);
84 OutputDesc *readOverlaySectionDescription();
85 OutputDesc *readOutputSectionDescription(StringRef outSec);
86 SmallVector<SectionCommand *, 0> readOverlay();
87 SectionClassDesc *readSectionClassDescription();
88 StringRef readSectionClassName();
89 SmallVector<StringRef, 0> readOutputSectionPhdrs();
90 std::pair<uint64_t, uint64_t> readInputSectionFlags();
91 InputSectionDescription *readInputSectionDescription(StringRef tok);
92 StringMatcher readFilePatterns();
93 SmallVector<SectionPattern, 0> readInputSectionsList();
94 InputSectionDescription *readInputSectionRules(StringRef filePattern,
95 uint64_t withFlags,
96 uint64_t withoutFlags);
97 unsigned readPhdrType();
98 SortSectionPolicy peekSortKind();
99 SortSectionPolicy readSortKind();
100 SymbolAssignment *readProvideHidden(bool provide, bool hidden);
101 SymbolAssignment *readAssignment(StringRef tok);
102 void readSort();
103 Expr readAssert();
104 Expr readConstant();
105 Expr getPageSize();
106
107 Expr readMemoryAssignment(StringRef, StringRef, StringRef);
108 void readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
109 uint32_t &negFlags, uint32_t &negInvFlags);
110
111 Expr combine(StringRef op, Expr l, Expr r);
112 Expr readExpr();
113 Expr readExpr1(Expr lhs, int minPrec);
114 StringRef readParenName();
115 Expr readPrimary();
116 Expr readTernary(Expr cond);
117 Expr readParenExpr();
118
119 // For parsing version script.
120 SmallVector<SymbolVersion, 0> readVersionExtern();
121 void readAnonymousDeclaration();
122 void readVersionDeclaration(StringRef verStr);
123
124 std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
125 readSymbols();
126
127 Ctx &ctx;
128
129 // If we are currently parsing a PROVIDE|PROVIDE_HIDDEN command,
130 // then this member is set to the PROVIDE symbol name.
131 std::optional<llvm::StringRef> activeProvideSym;
132};
133} // namespace
134
135static StringRef unquote(StringRef s) {
136 if (s.starts_with(Prefix: "\""))
137 return s.substr(Start: 1, N: s.size() - 2);
138 return s;
139}
140
141// Some operations only support one non absolute value. Move the
142// absolute one to the right hand side for convenience.
143static void moveAbsRight(LinkerScript &s, ExprValue &a, ExprValue &b) {
144 if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
145 std::swap(a&: a, b&: b);
146 if (!b.isAbsolute())
147 s.recordError(msg: a.loc +
148 ": at least one side of the expression must be absolute");
149}
150
151static ExprValue add(LinkerScript &s, ExprValue a, ExprValue b) {
152 moveAbsRight(s, a, b);
153 return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
154}
155
156static ExprValue sub(ExprValue a, ExprValue b) {
157 // The distance between two symbols in sections is absolute.
158 if (!a.isAbsolute() && !b.isAbsolute())
159 return a.getValue() - b.getValue();
160 return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
161}
162
163static ExprValue bitAnd(LinkerScript &s, ExprValue a, ExprValue b) {
164 moveAbsRight(s, a, b);
165 return {a.sec, a.forceAbsolute,
166 (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
167}
168
169static ExprValue bitXor(LinkerScript &s, ExprValue a, ExprValue b) {
170 moveAbsRight(s, a, b);
171 return {a.sec, a.forceAbsolute,
172 (a.getValue() ^ b.getValue()) - a.getSecAddr(), a.loc};
173}
174
175static ExprValue bitOr(LinkerScript &s, ExprValue a, ExprValue b) {
176 moveAbsRight(s, a, b);
177 return {a.sec, a.forceAbsolute,
178 (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
179}
180
181void ScriptParser::readDynamicList() {
182 SaveAndRestore saved(lexState, State::VersionNode);
183 expect(expect: "{");
184 SmallVector<SymbolVersion, 0> locals;
185 SmallVector<SymbolVersion, 0> globals;
186 std::tie(args&: locals, args&: globals) = readSymbols();
187 expect(expect: ";");
188
189 StringRef tok = peek();
190 if (tok.size()) {
191 setError("EOF expected, but got " + tok);
192 return;
193 }
194 if (!locals.empty()) {
195 setError("\"local:\" scope not supported in --dynamic-list");
196 return;
197 }
198
199 for (SymbolVersion v : globals)
200 ctx.arg.dynamicList.push_back(Elt: v);
201}
202
203void ScriptParser::readVersionScript() {
204 readVersionScriptCommand();
205 StringRef tok = peek();
206 if (tok.size())
207 setError("EOF expected, but got " + tok);
208}
209
210void ScriptParser::readVersionScriptCommand() {
211 SaveAndRestore saved(lexState, State::VersionNode);
212 if (consume(tok: "{")) {
213 readAnonymousDeclaration();
214 return;
215 }
216
217 if (atEOF())
218 setError("unexpected EOF");
219 while (peek() != "}" && !atEOF()) {
220 StringRef verStr = next();
221 if (verStr == "{") {
222 setError("anonymous version definition is used in "
223 "combination with other version definitions");
224 return;
225 }
226 expect(expect: "{");
227 readVersionDeclaration(verStr);
228 }
229}
230
231void ScriptParser::readVersion() {
232 expect(expect: "{");
233 readVersionScriptCommand();
234 expect(expect: "}");
235}
236
237void ScriptParser::readLinkerScript() {
238 while (!atEOF()) {
239 StringRef tok = next();
240 if (atEOF())
241 break;
242 if (tok == ";")
243 continue;
244
245 if (tok == "ENTRY") {
246 readEntry();
247 } else if (tok == "EXTERN") {
248 readExtern();
249 } else if (tok == "GROUP") {
250 readGroup();
251 } else if (tok == "INCLUDE") {
252 readInclude();
253 } else if (tok == "INPUT") {
254 readInput();
255 } else if (tok == "MEMORY") {
256 readMemory();
257 } else if (tok == "OUTPUT") {
258 readOutput();
259 } else if (tok == "OUTPUT_ARCH") {
260 readOutputArch();
261 } else if (tok == "OUTPUT_FORMAT") {
262 readOutputFormat();
263 } else if (tok == "OVERWRITE_SECTIONS") {
264 readOverwriteSections();
265 } else if (tok == "PHDRS") {
266 readPhdrs();
267 } else if (tok == "REGION_ALIAS") {
268 readRegionAlias();
269 } else if (tok == "SEARCH_DIR") {
270 readSearchDir();
271 } else if (tok == "SECTIONS") {
272 readSections();
273 } else if (tok == "TARGET") {
274 readTarget();
275 } else if (tok == "VERSION") {
276 readVersion();
277 } else if (tok == "NOCROSSREFS") {
278 readNoCrossRefs(/*to=*/false);
279 } else if (tok == "NOCROSSREFS_TO") {
280 readNoCrossRefs(/*to=*/true);
281 } else if (SymbolAssignment *cmd = readAssignment(tok)) {
282 ctx.script->sectionCommands.push_back(Elt: cmd);
283 } else {
284 setError("unknown directive: " + tok);
285 }
286 }
287}
288
289void ScriptParser::readDefsym() {
290 if (errCount(ctx))
291 return;
292 SaveAndRestore saved(lexState, State::Expr);
293 StringRef name = readName();
294 expect(expect: "=");
295 Expr e = readExpr();
296 if (!atEOF())
297 setError("EOF expected, but got " + next());
298 auto *cmd = make<SymbolAssignment>(
299 args&: name, args&: e, args: 0, args: getCurrentMB().getBufferIdentifier().str());
300 ctx.script->sectionCommands.push_back(Elt: cmd);
301}
302
303void ScriptParser::readNoCrossRefs(bool to) {
304 expect(expect: "(");
305 NoCrossRefCommand cmd{.outputSections: {}, .toFirst: to};
306 while (auto tok = till(tok: ")"))
307 cmd.outputSections.push_back(Elt: unquote(s: tok));
308 if (cmd.outputSections.size() < 2)
309 Warn(ctx) << getCurrentLocation()
310 << ": ignored with fewer than 2 output sections";
311 else
312 ctx.script->noCrossRefs.push_back(Elt: std::move(cmd));
313}
314
315void ScriptParser::addFile(StringRef s) {
316 if (curBuf.isUnderSysroot && s.starts_with(Prefix: "/")) {
317 SmallString<128> pathData;
318 StringRef path = (ctx.arg.sysroot + s).toStringRef(Out&: pathData);
319 if (sys::fs::exists(Path: path))
320 ctx.driver.addFile(path: ctx.saver.save(S: path), /*withLOption=*/false);
321 else
322 setError("cannot find " + s + " inside " + ctx.arg.sysroot);
323 return;
324 }
325
326 if (s.starts_with(Prefix: "/")) {
327 // Case 1: s is an absolute path. Just open it.
328 ctx.driver.addFile(path: s, /*withLOption=*/false);
329 } else if (s.starts_with(Prefix: "=")) {
330 // Case 2: relative to the sysroot.
331 if (ctx.arg.sysroot.empty())
332 ctx.driver.addFile(path: s.substr(Start: 1), /*withLOption=*/false);
333 else
334 ctx.driver.addFile(path: ctx.saver.save(S: ctx.arg.sysroot + "/" + s.substr(Start: 1)),
335 /*withLOption=*/false);
336 } else if (s.starts_with(Prefix: "-l")) {
337 // Case 3: search in the list of library paths.
338 ctx.driver.addLibrary(name: s.substr(Start: 2));
339 } else {
340 // Case 4: s is a relative path. Search in the directory of the script file.
341 std::string filename = std::string(getCurrentMB().getBufferIdentifier());
342 StringRef directory = sys::path::parent_path(path: filename);
343 if (!directory.empty()) {
344 SmallString<0> path(directory);
345 sys::path::append(path, a: s);
346 if (sys::fs::exists(Path: path)) {
347 ctx.driver.addFile(path, /*withLOption=*/false);
348 return;
349 }
350 }
351 // Then search in the current working directory.
352 if (sys::fs::exists(Path: s)) {
353 ctx.driver.addFile(path: s, /*withLOption=*/false);
354 } else {
355 // Finally, search in the list of library paths.
356 if (std::optional<std::string> path = findFromSearchPaths(ctx, path: s))
357 ctx.driver.addFile(path: ctx.saver.save(S: *path), /*withLOption=*/true);
358 else
359 setError("unable to find " + s);
360 }
361 }
362}
363
364void ScriptParser::readAsNeeded() {
365 expect(expect: "(");
366 bool orig = ctx.arg.asNeeded;
367 ctx.arg.asNeeded = true;
368 while (auto tok = till(tok: ")"))
369 addFile(s: unquote(s: tok));
370 ctx.arg.asNeeded = orig;
371}
372
373void ScriptParser::readEntry() {
374 // -e <symbol> takes predecence over ENTRY(<symbol>).
375 expect(expect: "(");
376 StringRef name = readName();
377 if (ctx.arg.entry.empty())
378 ctx.arg.entry = name;
379 expect(expect: ")");
380}
381
382void ScriptParser::readExtern() {
383 expect(expect: "(");
384 while (auto tok = till(tok: ")"))
385 ctx.arg.undefined.push_back(Elt: unquote(s: tok));
386}
387
388void ScriptParser::readGroup() {
389 SaveAndRestore saved(ctx.driver.isInGroup, true);
390 readInput();
391 if (!saved.get())
392 ++ctx.driver.nextGroupId;
393}
394
395void ScriptParser::readInclude() {
396 StringRef name = readName();
397 if (!activeFilenames.insert(V: name).second) {
398 setError("there is a cycle in linker script INCLUDEs");
399 return;
400 }
401
402 if (std::optional<std::string> path = searchScript(ctx, path: name)) {
403 if (std::optional<MemoryBufferRef> mb = readFile(ctx, path: *path)) {
404 buffers.push_back(Elt: curBuf);
405 curBuf = Buffer(ctx, *mb);
406 mbs.push_back(x: *mb);
407 }
408 return;
409 }
410 setError("cannot find linker script " + name);
411}
412
413void ScriptParser::readInput() {
414 expect(expect: "(");
415 while (auto tok = till(tok: ")")) {
416 if (tok == "AS_NEEDED")
417 readAsNeeded();
418 else
419 addFile(s: unquote(s: tok));
420 }
421}
422
423void ScriptParser::readOutput() {
424 // -o <file> takes predecence over OUTPUT(<file>).
425 expect(expect: "(");
426 StringRef name = readName();
427 if (ctx.arg.outputFile.empty())
428 ctx.arg.outputFile = name;
429 expect(expect: ")");
430}
431
432void ScriptParser::readOutputArch() {
433 // OUTPUT_ARCH is ignored for now.
434 expect(expect: "(");
435 while (till(tok: ")"))
436 ;
437}
438
439static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
440 return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
441 .Case(S: "elf32-i386", Value: {ELF32LEKind, EM_386})
442 .Case(S: "elf32-avr", Value: {ELF32LEKind, EM_AVR})
443 .Case(S: "elf32-iamcu", Value: {ELF32LEKind, EM_IAMCU})
444 .Case(S: "elf32-littlearm", Value: {ELF32LEKind, EM_ARM})
445 .Case(S: "elf32-bigarm", Value: {ELF32BEKind, EM_ARM})
446 .Case(S: "elf32-x86-64", Value: {ELF32LEKind, EM_X86_64})
447 .Case(S: "elf64-aarch64", Value: {ELF64LEKind, EM_AARCH64})
448 .Case(S: "elf64-littleaarch64", Value: {ELF64LEKind, EM_AARCH64})
449 .Case(S: "elf64-bigaarch64", Value: {ELF64BEKind, EM_AARCH64})
450 .Case(S: "elf32-powerpc", Value: {ELF32BEKind, EM_PPC})
451 .Case(S: "elf32-powerpcle", Value: {ELF32LEKind, EM_PPC})
452 .Case(S: "elf64-powerpc", Value: {ELF64BEKind, EM_PPC64})
453 .Case(S: "elf64-powerpcle", Value: {ELF64LEKind, EM_PPC64})
454 .Case(S: "elf64-x86-64", Value: {ELF64LEKind, EM_X86_64})
455 .Cases(CaseStrings: {"elf32-tradbigmips", "elf32-bigmips"}, Value: {ELF32BEKind, EM_MIPS})
456 .Case(S: "elf32-ntradbigmips", Value: {ELF32BEKind, EM_MIPS})
457 .Case(S: "elf32-tradlittlemips", Value: {ELF32LEKind, EM_MIPS})
458 .Case(S: "elf32-ntradlittlemips", Value: {ELF32LEKind, EM_MIPS})
459 .Case(S: "elf64-tradbigmips", Value: {ELF64BEKind, EM_MIPS})
460 .Case(S: "elf64-tradlittlemips", Value: {ELF64LEKind, EM_MIPS})
461 .Case(S: "elf32-littleriscv", Value: {ELF32LEKind, EM_RISCV})
462 .Case(S: "elf64-littleriscv", Value: {ELF64LEKind, EM_RISCV})
463 .Case(S: "elf64-sparc", Value: {ELF64BEKind, EM_SPARCV9})
464 .Case(S: "elf32-msp430", Value: {ELF32LEKind, EM_MSP430})
465 .Case(S: "elf32-loongarch", Value: {ELF32LEKind, EM_LOONGARCH})
466 .Case(S: "elf64-loongarch", Value: {ELF64LEKind, EM_LOONGARCH})
467 .Case(S: "elf64-s390", Value: {ELF64BEKind, EM_S390})
468 .Cases(CaseStrings: {"elf32-hexagon", "elf32-littlehexagon"},
469 Value: {ELF32LEKind, EM_HEXAGON})
470 .Default(Value: {ELFNoneKind, EM_NONE});
471}
472
473// Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
474// big if -EB is specified, little if -EL is specified, or default if neither is
475// specified.
476void ScriptParser::readOutputFormat() {
477 expect(expect: "(");
478
479 StringRef s = readName();
480 if (!consume(tok: ")")) {
481 expect(expect: ",");
482 StringRef tmp = readName();
483 if (ctx.arg.optEB)
484 s = tmp;
485 expect(expect: ",");
486 tmp = readName();
487 if (ctx.arg.optEL)
488 s = tmp;
489 consume(tok: ")");
490 }
491 // If more than one OUTPUT_FORMAT is specified, only the first is checked.
492 if (!ctx.arg.bfdname.empty())
493 return;
494 ctx.arg.bfdname = s;
495
496 if (s == "binary") {
497 ctx.arg.oFormatBinary = true;
498 return;
499 }
500
501 if (s.consume_back(Suffix: "-freebsd"))
502 ctx.arg.osabi = ELFOSABI_FREEBSD;
503
504 std::tie(args&: ctx.arg.ekind, args&: ctx.arg.emachine) = parseBfdName(s);
505 if (ctx.arg.emachine == EM_NONE)
506 setError("unknown output format name: " + ctx.arg.bfdname);
507 if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
508 ctx.arg.mipsN32Abi = true;
509 if (ctx.arg.emachine == EM_MSP430)
510 ctx.arg.osabi = ELFOSABI_STANDALONE;
511}
512
513void ScriptParser::readPhdrs() {
514 expect(expect: "{");
515 while (auto tok = till(tok: "}")) {
516 PhdrsCommand cmd;
517 cmd.name = tok;
518 cmd.type = readPhdrType();
519
520 while (!errCount(ctx) && !consume(tok: ";")) {
521 if (consume(tok: "FILEHDR"))
522 cmd.hasFilehdr = true;
523 else if (consume(tok: "PHDRS"))
524 cmd.hasPhdrs = true;
525 else if (consume(tok: "AT"))
526 cmd.lmaExpr = readParenExpr();
527 else if (consume(tok: "FLAGS"))
528 cmd.flags = readParenExpr()().getValue();
529 else
530 setError("unexpected header attribute: " + next());
531 }
532
533 ctx.script->phdrsCommands.push_back(Elt: cmd);
534 }
535}
536
537void ScriptParser::readRegionAlias() {
538 expect(expect: "(");
539 StringRef alias = readName();
540 expect(expect: ",");
541 StringRef name = readName();
542 expect(expect: ")");
543
544 if (ctx.script->memoryRegions.contains(Key: alias))
545 setError("redefinition of memory region '" + alias + "'");
546 if (!ctx.script->memoryRegions.contains(Key: name))
547 setError("memory region '" + name + "' is not defined");
548 ctx.script->memoryRegions.insert(KV: {alias, ctx.script->memoryRegions[name]});
549}
550
551void ScriptParser::readSearchDir() {
552 expect(expect: "(");
553 StringRef name = readName();
554 if (!ctx.arg.nostdlib)
555 ctx.arg.searchPaths.push_back(Elt: name);
556 expect(expect: ")");
557}
558
559// This reads an overlay description. Overlays are used to describe output
560// sections that use the same virtual memory range and normally would trigger
561// linker's sections sanity check failures.
562// https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
563SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() {
564 Expr addrExpr;
565 if (!consume(tok: ":")) {
566 addrExpr = readExpr();
567 expect(expect: ":");
568 }
569 bool noCrossRefs = consume(tok: "NOCROSSREFS");
570 Expr lmaExpr = consume(tok: "AT") ? readParenExpr() : Expr{};
571 expect(expect: "{");
572
573 SmallVector<SectionCommand *, 0> v;
574 OutputSection *prev = nullptr;
575 while (!errCount(ctx) && !consume(tok: "}")) {
576 // VA is the same for all sections. The LMAs are consecutive in memory
577 // starting from the base load address.
578 OutputDesc *osd = readOverlaySectionDescription();
579 osd->osec.addrExpr = addrExpr;
580 if (prev) {
581 osd->osec.lmaExpr = [=] { return prev->getLMA() + prev->size; };
582 } else {
583 osd->osec.lmaExpr = lmaExpr;
584 // Use first section address for subsequent sections. Ensure the first
585 // section, even if empty, is not discarded.
586 osd->osec.usedInExpression = true;
587 addrExpr = [=]() -> ExprValue { return {&osd->osec, false, 0, ""}; };
588 }
589 v.push_back(Elt: osd);
590 prev = &osd->osec;
591 }
592 if (!v.empty())
593 static_cast<OutputDesc *>(v.front())->osec.firstInOverlay = true;
594 if (consume(tok: ">")) {
595 StringRef regionName = readName();
596 for (SectionCommand *od : v)
597 static_cast<OutputDesc *>(od)->osec.memoryRegionName =
598 std::string(regionName);
599 }
600 if (noCrossRefs) {
601 NoCrossRefCommand cmd;
602 for (SectionCommand *od : v)
603 cmd.outputSections.push_back(Elt: static_cast<OutputDesc *>(od)->osec.name);
604 ctx.script->noCrossRefs.push_back(Elt: std::move(cmd));
605 }
606
607 // According to the specification, at the end of the overlay, the location
608 // counter should be equal to the overlay base address plus size of the
609 // largest section seen in the overlay.
610 // Here we want to create the Dot assignment command to achieve that.
611 Expr moveDot = [=] {
612 uint64_t max = 0;
613 for (SectionCommand *cmd : v)
614 max = std::max(a: max, b: cast<OutputDesc>(Val: cmd)->osec.size);
615 return addrExpr().getValue() + max;
616 };
617 v.push_back(Elt: make<SymbolAssignment>(args: ".", args&: moveDot, args: 0, args: getCurrentLocation()));
618 return v;
619}
620
621SectionClassDesc *ScriptParser::readSectionClassDescription() {
622 StringRef name = readSectionClassName();
623 SectionClassDesc *desc = make<SectionClassDesc>(args&: name);
624 if (!ctx.script->sectionClasses.insert(KV: {CachedHashStringRef(name), desc})
625 .second)
626 setError("section class '" + name + "' already defined");
627 expect(expect: "{");
628 while (auto tok = till(tok: "}")) {
629 if (tok == "(" || tok == ")") {
630 setError("expected filename pattern");
631 } else if (peek() == "(") {
632 InputSectionDescription *isd = readInputSectionDescription(tok);
633 if (!isd->classRef.empty())
634 setError("section class '" + name + "' references class '" +
635 isd->classRef + "'");
636 desc->sc.commands.push_back(Elt: isd);
637 }
638 }
639 return desc;
640}
641
642StringRef ScriptParser::readSectionClassName() {
643 expect(expect: "(");
644 StringRef name = unquote(s: next());
645 expect(expect: ")");
646 return name;
647}
648
649void ScriptParser::readOverwriteSections() {
650 expect(expect: "{");
651 while (auto tok = till(tok: "}"))
652 ctx.script->overwriteSections.push_back(Elt: readOutputSectionDescription(outSec: tok));
653}
654
655void ScriptParser::readSections() {
656 expect(expect: "{");
657 SmallVector<SectionCommand *, 0> v;
658 while (auto tok = till(tok: "}")) {
659 if (tok == "OVERLAY") {
660 for (SectionCommand *cmd : readOverlay())
661 v.push_back(Elt: cmd);
662 continue;
663 }
664 if (tok == "CLASS") {
665 v.push_back(Elt: readSectionClassDescription());
666 continue;
667 }
668 if (tok == "INCLUDE") {
669 readInclude();
670 continue;
671 }
672
673 if (SectionCommand *cmd = readAssignment(tok))
674 v.push_back(Elt: cmd);
675 else
676 v.push_back(Elt: readOutputSectionDescription(outSec: tok));
677 }
678
679 // If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN,
680 // the relro fields should be cleared.
681 if (!ctx.script->seenRelroEnd)
682 for (SectionCommand *cmd : v)
683 if (auto *osd = dyn_cast<OutputDesc>(Val: cmd))
684 osd->osec.relro = false;
685
686 ctx.script->sectionCommands.insert(I: ctx.script->sectionCommands.end(),
687 From: v.begin(), To: v.end());
688
689 if (atEOF() || !consume(tok: "INSERT")) {
690 ctx.script->hasSectionsCommand = true;
691 return;
692 }
693
694 bool isAfter = false;
695 if (consume(tok: "AFTER"))
696 isAfter = true;
697 else if (!consume(tok: "BEFORE"))
698 setError("expected AFTER/BEFORE, but got '" + next() + "'");
699 StringRef where = readName();
700 SmallVector<StringRef, 0> names;
701 for (SectionCommand *cmd : v)
702 if (auto *os = dyn_cast<OutputDesc>(Val: cmd))
703 names.push_back(Elt: os->osec.name);
704 if (!names.empty())
705 ctx.script->insertCommands.push_back(Elt: {.names: std::move(names), .isAfter: isAfter, .where: where});
706}
707
708void ScriptParser::readTarget() {
709 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
710 // we accept only a limited set of BFD names (i.e. "elf" or "binary")
711 // for --format. We recognize only /^elf/ and "binary" in the linker
712 // script as well.
713 expect(expect: "(");
714 StringRef tok = readName();
715 expect(expect: ")");
716
717 if (tok.starts_with(Prefix: "elf"))
718 ctx.arg.formatBinary = false;
719 else if (tok == "binary")
720 ctx.arg.formatBinary = true;
721 else
722 setError("unknown target: " + tok);
723}
724
725static int precedence(StringRef op) {
726 return StringSwitch<int>(op)
727 .Cases(CaseStrings: {"*", "/", "%"}, Value: 11)
728 .Cases(CaseStrings: {"+", "-"}, Value: 10)
729 .Cases(CaseStrings: {"<<", ">>"}, Value: 9)
730 .Cases(CaseStrings: {"<", "<=", ">", ">="}, Value: 8)
731 .Cases(CaseStrings: {"==", "!="}, Value: 7)
732 .Case(S: "&", Value: 6)
733 .Case(S: "^", Value: 5)
734 .Case(S: "|", Value: 4)
735 .Case(S: "&&", Value: 3)
736 .Case(S: "||", Value: 2)
737 .Case(S: "?", Value: 1)
738 .Default(Value: -1);
739}
740
741StringMatcher ScriptParser::readFilePatterns() {
742 StringMatcher Matcher;
743 while (auto tok = till(tok: ")"))
744 Matcher.addPattern(Matcher: SingleStringMatcher(tok));
745 return Matcher;
746}
747
748SortSectionPolicy ScriptParser::peekSortKind() {
749 return StringSwitch<SortSectionPolicy>(peek())
750 .Case(S: "REVERSE", Value: SortSectionPolicy::Reverse)
751 .Cases(CaseStrings: {"SORT", "SORT_BY_NAME"}, Value: SortSectionPolicy::Name)
752 .Case(S: "SORT_BY_ALIGNMENT", Value: SortSectionPolicy::Alignment)
753 .Case(S: "SORT_BY_INIT_PRIORITY", Value: SortSectionPolicy::Priority)
754 .Case(S: "SORT_NONE", Value: SortSectionPolicy::None)
755 .Default(Value: SortSectionPolicy::Default);
756}
757
758SortSectionPolicy ScriptParser::readSortKind() {
759 SortSectionPolicy ret = peekSortKind();
760 if (ret != SortSectionPolicy::Default)
761 skip();
762 return ret;
763}
764
765// Reads SECTIONS command contents in the following form:
766//
767// <contents> ::= <elem>*
768// <elem> ::= <exclude>? <glob-pattern>
769// <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
770//
771// For example,
772//
773// *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
774//
775// is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
776// The semantics of that is section .foo in any file, section .bar in
777// any file but a.o, and section .baz in any file but b.o.
778SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() {
779 SmallVector<SectionPattern, 0> ret;
780 while (!errCount(ctx) && peek() != ")") {
781 StringMatcher excludeFilePat;
782 if (consume(tok: "EXCLUDE_FILE")) {
783 expect(expect: "(");
784 excludeFilePat = readFilePatterns();
785 }
786
787 StringMatcher SectionMatcher;
788 // Break if the next token is ), EXCLUDE_FILE, or SORT*.
789 while (!errCount(ctx) && peekSortKind() == SortSectionPolicy::Default) {
790 StringRef s = peek();
791 if (s == ")" || s == "EXCLUDE_FILE")
792 break;
793 // Detect common mistakes when certain non-wildcard meta characters are
794 // used without a closing ')'.
795 if (!s.empty() && strchr(s: "(){}", c: s[0])) {
796 skip();
797 setError("section pattern is expected");
798 break;
799 }
800 SectionMatcher.addPattern(Matcher: readName());
801 }
802
803 if (!SectionMatcher.empty())
804 ret.push_back(Elt: {std::move(excludeFilePat), std::move(SectionMatcher)});
805 else if (excludeFilePat.empty())
806 break;
807 else
808 setError("section pattern is expected");
809 }
810 return ret;
811}
812
813// Reads contents of "SECTIONS" directive. That directive contains a
814// list of glob patterns for input sections. The grammar is as follows.
815//
816// <patterns> ::= <section-list>
817// | <sort> "(" <section-list> ")"
818// | <sort> "(" <sort> "(" <section-list> ")" ")"
819//
820// <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
821// | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
822//
823// <section-list> is parsed by readInputSectionsList().
824InputSectionDescription *
825ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
826 uint64_t withoutFlags) {
827 auto *cmd =
828 make<InputSectionDescription>(args&: filePattern, args&: withFlags, args&: withoutFlags);
829 expect(expect: "(");
830
831 while (peek() != ")" && !atEOF()) {
832 SortSectionPolicy outer = readSortKind();
833 SortSectionPolicy inner = SortSectionPolicy::Default;
834 SmallVector<SectionPattern, 0> v;
835 if (outer != SortSectionPolicy::Default) {
836 expect(expect: "(");
837 inner = readSortKind();
838 if (inner != SortSectionPolicy::Default) {
839 expect(expect: "(");
840 v = readInputSectionsList();
841 expect(expect: ")");
842 } else {
843 v = readInputSectionsList();
844 }
845 expect(expect: ")");
846 } else {
847 v = readInputSectionsList();
848 }
849
850 for (SectionPattern &pat : v) {
851 pat.sortInner = inner;
852 pat.sortOuter = outer;
853 }
854
855 std::move(first: v.begin(), last: v.end(), result: std::back_inserter(x&: cmd->sectionPatterns));
856 }
857 expect(expect: ")");
858 return cmd;
859}
860
861InputSectionDescription *
862ScriptParser::readInputSectionDescription(StringRef tok) {
863 // Input section wildcard can be surrounded by KEEP.
864 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
865 uint64_t withFlags = 0;
866 uint64_t withoutFlags = 0;
867 if (tok == "KEEP") {
868 expect(expect: "(");
869 if (consume(tok: "INPUT_SECTION_FLAGS"))
870 std::tie(args&: withFlags, args&: withoutFlags) = readInputSectionFlags();
871
872 tok = next();
873 InputSectionDescription *cmd;
874 if (tok == "CLASS")
875 cmd = make<InputSectionDescription>(args: StringRef{}, args&: withFlags, args&: withoutFlags,
876 args: readSectionClassName());
877 else
878 cmd = readInputSectionRules(filePattern: tok, withFlags, withoutFlags);
879 expect(expect: ")");
880 ctx.script->keptSections.push_back(Elt: cmd);
881 return cmd;
882 }
883 if (tok == "INPUT_SECTION_FLAGS") {
884 std::tie(args&: withFlags, args&: withoutFlags) = readInputSectionFlags();
885 tok = next();
886 }
887 if (tok == "CLASS")
888 return make<InputSectionDescription>(args: StringRef{}, args&: withFlags, args&: withoutFlags,
889 args: readSectionClassName());
890 return readInputSectionRules(filePattern: tok, withFlags, withoutFlags);
891}
892
893void ScriptParser::readSort() {
894 expect(expect: "(");
895 expect(expect: "CONSTRUCTORS");
896 expect(expect: ")");
897}
898
899Expr ScriptParser::readAssert() {
900 expect(expect: "(");
901 Expr e = readExpr();
902 expect(expect: ",");
903 StringRef msg = readName();
904 expect(expect: ")");
905
906 return [=, s = ctx.script]() -> ExprValue {
907 if (!e().getValue())
908 s->recordError(msg);
909 return s->getDot();
910 };
911}
912
913#define ECase(X) \
914 { #X, X }
915constexpr std::pair<const char *, unsigned> typeMap[] = {
916 ECase(SHT_PROGBITS), ECase(SHT_NOTE), ECase(SHT_NOBITS),
917 ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY),
918};
919#undef ECase
920
921// Tries to read the special directive for an output section definition which
922// can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
923// "(TYPE=<value>)".
924bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok) {
925 if (tok != "NOLOAD" && tok != "COPY" && tok != "INFO" && tok != "OVERLAY" &&
926 tok != "TYPE")
927 return false;
928
929 if (consume(tok: "NOLOAD")) {
930 cmd->type = SHT_NOBITS;
931 cmd->typeIsSet = true;
932 } else if (consume(tok: "TYPE")) {
933 expect(expect: "=");
934 StringRef value = peek();
935 auto it = llvm::find_if(Range: typeMap, P: [=](auto e) { return e.first == value; });
936 if (it != std::end(arr: typeMap)) {
937 // The value is a recognized literal SHT_*.
938 cmd->type = it->second;
939 skip();
940 } else if (value.starts_with(Prefix: "SHT_")) {
941 setError("unknown section type " + value);
942 } else {
943 // Otherwise, read an expression.
944 cmd->type = readExpr()().getValue();
945 }
946 cmd->typeIsSet = true;
947 } else {
948 skip(); // This is "COPY", "INFO" or "OVERLAY".
949 cmd->nonAlloc = true;
950 }
951 expect(expect: ")");
952 return true;
953}
954
955// Reads an expression and/or the special directive for an output
956// section definition. Directive is one of following: "(NOLOAD)",
957// "(COPY)", "(INFO)" or "(OVERLAY)".
958//
959// An output section name can be followed by an address expression
960// and/or directive. This grammar is not LL(1) because "(" can be
961// interpreted as either the beginning of some expression or beginning
962// of directive.
963//
964// https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
965// https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
966void ScriptParser::readSectionAddressType(OutputSection *cmd) {
967 if (consume(tok: "(")) {
968 // Temporarily set lexState to support TYPE=<value> without spaces.
969 SaveAndRestore saved(lexState, State::Expr);
970 if (readSectionDirective(cmd, tok: peek()))
971 return;
972 cmd->addrExpr = readExpr();
973 expect(expect: ")");
974 } else {
975 cmd->addrExpr = readExpr();
976 }
977
978 if (consume(tok: "(")) {
979 SaveAndRestore saved(lexState, State::Expr);
980 StringRef tok = peek();
981 if (!readSectionDirective(cmd, tok))
982 setError("unknown section directive: " + tok);
983 }
984}
985
986static Expr checkAlignment(Ctx &ctx, Expr e, std::string &loc) {
987 return [=, &ctx] {
988 uint64_t alignment = std::max(a: (uint64_t)1, b: e().getValue());
989 if (!isPowerOf2_64(Value: alignment)) {
990 ErrAlways(ctx) << loc << ": alignment must be power of 2";
991 return (uint64_t)1; // Return a dummy value.
992 }
993 return alignment;
994 };
995}
996
997OutputDesc *ScriptParser::readOverlaySectionDescription() {
998 OutputDesc *osd =
999 ctx.script->createOutputSection(name: readName(), location: getCurrentLocation());
1000 osd->osec.inOverlay = true;
1001 expect(expect: "{");
1002 while (auto tok = till(tok: "}"))
1003 osd->osec.commands.push_back(Elt: readInputSectionDescription(tok));
1004 osd->osec.phdrs = readOutputSectionPhdrs();
1005 return osd;
1006}
1007
1008OutputDesc *ScriptParser::readOutputSectionDescription(StringRef outSec) {
1009 OutputDesc *cmd =
1010 ctx.script->createOutputSection(name: unquote(s: outSec), location: getCurrentLocation());
1011 OutputSection *osec = &cmd->osec;
1012 // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.
1013 osec->relro = ctx.script->seenDataAlign && !ctx.script->seenRelroEnd;
1014
1015 size_t symbolsReferenced = ctx.script->referencedSymbols.size();
1016
1017 if (peek() != ":")
1018 readSectionAddressType(cmd: osec);
1019 expect(expect: ":");
1020
1021 std::string location = getCurrentLocation();
1022 if (consume(tok: "AT"))
1023 osec->lmaExpr = readParenExpr();
1024 if (consume(tok: "ALIGN"))
1025 osec->alignExpr = checkAlignment(ctx, e: readParenExpr(), loc&: location);
1026 if (consume(tok: "SUBALIGN"))
1027 osec->subalignExpr = checkAlignment(ctx, e: readParenExpr(), loc&: location);
1028
1029 // Parse constraints.
1030 if (consume(tok: "ONLY_IF_RO"))
1031 osec->constraint = ConstraintKind::ReadOnly;
1032 if (consume(tok: "ONLY_IF_RW"))
1033 osec->constraint = ConstraintKind::ReadWrite;
1034 expect(expect: "{");
1035
1036 while (auto tok = till(tok: "}")) {
1037 if (tok == ";") {
1038 // Empty commands are allowed. Do nothing here.
1039 } else if (SymbolAssignment *assign = readAssignment(tok)) {
1040 osec->commands.push_back(Elt: assign);
1041 } else if (ByteCommand *data = readByteCommand(tok)) {
1042 osec->commands.push_back(Elt: data);
1043 } else if (tok == "CONSTRUCTORS") {
1044 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1045 // by name. This is for very old file formats such as ECOFF/XCOFF.
1046 // For ELF, we should ignore.
1047 } else if (tok == "FILL") {
1048 // We handle the FILL command as an alias for =fillexp section attribute,
1049 // which is different from what GNU linkers do.
1050 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1051 if (peek() != "(")
1052 setError("( expected, but got " + peek());
1053 osec->filler = readFill();
1054 } else if (tok == "SORT") {
1055 readSort();
1056 } else if (tok == "INCLUDE") {
1057 readInclude();
1058 } else if (tok == "(" || tok == ")") {
1059 setError("expected filename pattern");
1060 } else if (peek() == "(") {
1061 osec->commands.push_back(Elt: readInputSectionDescription(tok));
1062 } else {
1063 // We have a file name and no input sections description. It is not a
1064 // commonly used syntax, but still acceptable. In that case, all sections
1065 // from the file will be included.
1066 // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
1067 // handle this case here as it will already have been matched by the
1068 // case above.
1069 auto *isd = make<InputSectionDescription>(args&: tok);
1070 isd->sectionPatterns.push_back(Elt: {{}, StringMatcher("*")});
1071 osec->commands.push_back(Elt: isd);
1072 }
1073 }
1074
1075 if (consume(tok: ">"))
1076 osec->memoryRegionName = std::string(readName());
1077
1078 if (consume(tok: "AT")) {
1079 expect(expect: ">");
1080 osec->lmaRegionName = std::string(readName());
1081 }
1082
1083 if (osec->lmaExpr && !osec->lmaRegionName.empty())
1084 ErrAlways(ctx) << "section can't have both LMA and a load region";
1085
1086 osec->phdrs = readOutputSectionPhdrs();
1087
1088 if (peek() == "=" || peek().starts_with(Prefix: "=")) {
1089 lexState = State::Expr;
1090 consume(tok: "=");
1091 osec->filler = readFill();
1092 lexState = State::Script;
1093 }
1094
1095 // Consume optional comma following output section command.
1096 consume(tok: ",");
1097
1098 if (ctx.script->referencedSymbols.size() > symbolsReferenced)
1099 osec->expressionsUseSymbols = true;
1100 return cmd;
1101}
1102
1103// Reads a `=<fillexp>` expression and returns its value as a big-endian number.
1104// https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1105// We do not support using symbols in such expressions.
1106//
1107// When reading a hexstring, ld.bfd handles it as a blob of arbitrary
1108// size, while ld.gold always handles it as a 32-bit big-endian number.
1109// We are compatible with ld.gold because it's easier to implement.
1110// Also, we require that expressions with operators must be wrapped into
1111// round brackets. We did it to resolve the ambiguity when parsing scripts like:
1112// SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
1113std::array<uint8_t, 4> ScriptParser::readFill() {
1114 uint64_t value = readPrimary()().val;
1115 if (value > UINT32_MAX)
1116 setError("filler expression result does not fit 32-bit: 0x" +
1117 Twine::utohexstr(Val: value));
1118
1119 std::array<uint8_t, 4> buf;
1120 write32be(P: buf.data(), V: (uint32_t)value);
1121 return buf;
1122}
1123
1124SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
1125 expect(expect: "(");
1126 StringRef name = readName(), eq = peek();
1127 if (eq != "=") {
1128 setError("= expected, but got " + next());
1129 while (till(tok: ")"))
1130 ;
1131 return nullptr;
1132 }
1133 llvm::SaveAndRestore saveActiveProvideSym(activeProvideSym);
1134 if (provide)
1135 activeProvideSym = name;
1136 SymbolAssignment *cmd = readSymbolAssignment(name);
1137 cmd->provide = provide;
1138 cmd->hidden = hidden;
1139 expect(expect: ")");
1140 return cmd;
1141}
1142
1143// Replace whitespace sequence (including \n) with one single space. The output
1144// is used by -Map.
1145static void squeezeSpaces(std::string &str) {
1146 char prev = '\0';
1147 auto it = str.begin();
1148 for (char c : str)
1149 if (!isSpace(C: c) || (c = ' ') != prev)
1150 *it++ = prev = c;
1151 str.erase(first: it, last: str.end());
1152}
1153
1154SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
1155 // Assert expression returns Dot, so this is equal to ".=."
1156 if (tok == "ASSERT")
1157 return make<SymbolAssignment>(args: ".", args: readAssert(), args: 0, args: getCurrentLocation());
1158
1159 const char *oldS = prevTok.data();
1160 SymbolAssignment *cmd = nullptr;
1161 bool savedSeenRelroEnd = ctx.script->seenRelroEnd;
1162 const StringRef op = peek();
1163 {
1164 SaveAndRestore saved(lexState, State::Expr);
1165 if (op.starts_with(Prefix: "=")) {
1166 // Support = followed by an expression without whitespace.
1167 cmd = readSymbolAssignment(name: unquote(s: tok));
1168 } else if ((op.size() == 2 && op[1] == '=' && strchr(s: "+-*/&^|", c: op[0])) ||
1169 op == "<<=" || op == ">>=") {
1170 cmd = readSymbolAssignment(name: unquote(s: tok));
1171 } else if (tok == "PROVIDE") {
1172 cmd = readProvideHidden(provide: true, hidden: false);
1173 } else if (tok == "HIDDEN") {
1174 cmd = readProvideHidden(provide: false, hidden: true);
1175 } else if (tok == "PROVIDE_HIDDEN") {
1176 cmd = readProvideHidden(provide: true, hidden: true);
1177 }
1178 }
1179
1180 if (cmd) {
1181 cmd->dataSegmentRelroEnd = !savedSeenRelroEnd && ctx.script->seenRelroEnd;
1182 cmd->commandString = StringRef(oldS, curTok.data() - oldS).str();
1183 squeezeSpaces(str&: cmd->commandString);
1184 expect(expect: ";");
1185 }
1186 return cmd;
1187}
1188
1189StringRef ScriptParser::readName() { return unquote(s: next()); }
1190
1191SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1192 StringRef op = next();
1193 assert(op == "=" || op == "*=" || op == "/=" || op == "+=" || op == "-=" ||
1194 op == "&=" || op == "^=" || op == "|=" || op == "<<=" || op == ">>=");
1195 // Note: GNU ld does not support %=.
1196 Expr e = readExpr();
1197 if (op != "=") {
1198 std::string loc = getCurrentLocation();
1199 e = [=, s = ctx.script, c = op[0], &ctx = ctx]() -> ExprValue {
1200 ExprValue lhs = s->getSymbolValue(name, loc);
1201 switch (c) {
1202 case '*':
1203 return lhs.getValue() * e().getValue();
1204 case '/':
1205 if (uint64_t rv = e().getValue())
1206 return lhs.getValue() / rv;
1207 ErrAlways(ctx) << loc << ": division by zero";
1208 return 0;
1209 case '+':
1210 return add(s&: *s, a: lhs, b: e());
1211 case '-':
1212 return sub(a: lhs, b: e());
1213 case '<':
1214 return lhs.getValue() << e().getValue() % 64;
1215 case '>':
1216 return lhs.getValue() >> e().getValue() % 64;
1217 case '&':
1218 return lhs.getValue() & e().getValue();
1219 case '^':
1220 return lhs.getValue() ^ e().getValue();
1221 case '|':
1222 return lhs.getValue() | e().getValue();
1223 default:
1224 llvm_unreachable("");
1225 }
1226 };
1227 }
1228 return make<SymbolAssignment>(args&: name, args&: e, args: ctx.scriptSymOrderCounter++,
1229 args: getCurrentLocation());
1230}
1231
1232// This is an operator-precedence parser to parse a linker
1233// script expression.
1234Expr ScriptParser::readExpr() {
1235 if (atEOF())
1236 return []() { return 0; };
1237 // Our lexer is context-aware. Set the in-expression bit so that
1238 // they apply different tokenization rules.
1239 SaveAndRestore saved(lexState, State::Expr);
1240 Expr e = readExpr1(lhs: readPrimary(), minPrec: 0);
1241 return e;
1242}
1243
1244Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
1245 if (op == "+")
1246 return [=, s = ctx.script] { return add(s&: *s, a: l(), b: r()); };
1247 if (op == "-")
1248 return [=] { return sub(a: l(), b: r()); };
1249 if (op == "*")
1250 return [=] { return l().getValue() * r().getValue(); };
1251 if (op == "/") {
1252 std::string loc = getCurrentLocation();
1253 return [=, &ctx = ctx]() -> uint64_t {
1254 if (uint64_t rv = r().getValue())
1255 return l().getValue() / rv;
1256 ErrAlways(ctx) << loc << ": division by zero";
1257 return 0;
1258 };
1259 }
1260 if (op == "%") {
1261 std::string loc = getCurrentLocation();
1262 return [=, &ctx = ctx]() -> uint64_t {
1263 if (uint64_t rv = r().getValue())
1264 return l().getValue() % rv;
1265 ErrAlways(ctx) << loc << ": modulo by zero";
1266 return 0;
1267 };
1268 }
1269 if (op == "<<")
1270 return [=] { return l().getValue() << r().getValue() % 64; };
1271 if (op == ">>")
1272 return [=] { return l().getValue() >> r().getValue() % 64; };
1273 if (op == "<")
1274 return [=] { return l().getValue() < r().getValue(); };
1275 if (op == ">")
1276 return [=] { return l().getValue() > r().getValue(); };
1277 if (op == ">=")
1278 return [=] { return l().getValue() >= r().getValue(); };
1279 if (op == "<=")
1280 return [=] { return l().getValue() <= r().getValue(); };
1281 if (op == "==")
1282 return [=] { return l().getValue() == r().getValue(); };
1283 if (op == "!=")
1284 return [=] { return l().getValue() != r().getValue(); };
1285 if (op == "||")
1286 return [=] { return l().getValue() || r().getValue(); };
1287 if (op == "&&")
1288 return [=] { return l().getValue() && r().getValue(); };
1289 if (op == "&")
1290 return [=, s = ctx.script] { return bitAnd(s&: *s, a: l(), b: r()); };
1291 if (op == "^")
1292 return [=, s = ctx.script] { return bitXor(s&: *s, a: l(), b: r()); };
1293 if (op == "|")
1294 return [=, s = ctx.script] { return bitOr(s&: *s, a: l(), b: r()); };
1295 llvm_unreachable("invalid operator");
1296}
1297
1298// This is a part of the operator-precedence parser. This function
1299// assumes that the remaining token stream starts with an operator.
1300Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1301 while (!atEOF() && !errCount(ctx)) {
1302 // Read an operator and an expression.
1303 StringRef op1 = peek();
1304 if (precedence(op: op1) < minPrec)
1305 break;
1306 skip();
1307 if (op1 == "?")
1308 return readTernary(cond: lhs);
1309 Expr rhs = readPrimary();
1310
1311 // Evaluate the remaining part of the expression first if the
1312 // next operator has greater precedence than the previous one.
1313 // For example, if we have read "+" and "3", and if the next
1314 // operator is "*", then we'll evaluate 3 * ... part first.
1315 while (!atEOF()) {
1316 StringRef op2 = peek();
1317 if (precedence(op: op2) <= precedence(op: op1))
1318 break;
1319 rhs = readExpr1(lhs: rhs, minPrec: precedence(op: op2));
1320 }
1321
1322 lhs = combine(op: op1, l: lhs, r: rhs);
1323 }
1324 return lhs;
1325}
1326
1327Expr ScriptParser::getPageSize() {
1328 std::string location = getCurrentLocation();
1329 return [=, &ctx = this->ctx]() -> uint64_t {
1330 if (ctx.target)
1331 return ctx.arg.commonPageSize;
1332 ErrAlways(ctx) << location << ": unable to calculate page size";
1333 return 4096; // Return a dummy value.
1334 };
1335}
1336
1337Expr ScriptParser::readConstant() {
1338 StringRef s = readParenName();
1339 if (s == "COMMONPAGESIZE")
1340 return getPageSize();
1341 if (s == "MAXPAGESIZE")
1342 return [&ctx = this->ctx] { return ctx.arg.maxPageSize; };
1343 setError("unknown constant: " + s);
1344 return [] { return 0; };
1345}
1346
1347// Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1348// "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1349// have "K" (Ki) or "M" (Mi) suffixes.
1350static std::optional<uint64_t> parseInt(StringRef tok) {
1351 // Hexadecimal
1352 uint64_t val;
1353 if (tok.starts_with_insensitive(Prefix: "0x")) {
1354 if (!to_integer(S: tok.substr(Start: 2), Num&: val, Base: 16))
1355 return std::nullopt;
1356 return val;
1357 }
1358 if (tok.ends_with_insensitive(Suffix: "H")) {
1359 if (!to_integer(S: tok.drop_back(), Num&: val, Base: 16))
1360 return std::nullopt;
1361 return val;
1362 }
1363
1364 // Decimal
1365 if (tok.ends_with_insensitive(Suffix: "K")) {
1366 if (!to_integer(S: tok.drop_back(), Num&: val, Base: 10))
1367 return std::nullopt;
1368 return val * 1024;
1369 }
1370 if (tok.ends_with_insensitive(Suffix: "M")) {
1371 if (!to_integer(S: tok.drop_back(), Num&: val, Base: 10))
1372 return std::nullopt;
1373 return val * 1024 * 1024;
1374 }
1375 if (!to_integer(S: tok, Num&: val, Base: 10))
1376 return std::nullopt;
1377 return val;
1378}
1379
1380ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
1381 int size = StringSwitch<int>(tok)
1382 .Case(S: "BYTE", Value: 1)
1383 .Case(S: "SHORT", Value: 2)
1384 .Case(S: "LONG", Value: 4)
1385 .Case(S: "QUAD", Value: 8)
1386 .Default(Value: -1);
1387 if (size == -1)
1388 return nullptr;
1389
1390 const char *oldS = prevTok.data();
1391 Expr e = readParenExpr();
1392 std::string commandString = StringRef(oldS, curBuf.s.data() - oldS).str();
1393 squeezeSpaces(str&: commandString);
1394 return make<ByteCommand>(args&: e, args&: size, args: std::move(commandString));
1395}
1396
1397static std::optional<uint64_t> parseFlag(StringRef tok) {
1398 if (std::optional<uint64_t> asInt = parseInt(tok))
1399 return asInt;
1400#define CASE_ENT(enum) #enum, ELF::enum
1401 return StringSwitch<std::optional<uint64_t>>(tok)
1402 .Case(CASE_ENT(SHF_WRITE))
1403 .Case(CASE_ENT(SHF_ALLOC))
1404 .Case(CASE_ENT(SHF_EXECINSTR))
1405 .Case(CASE_ENT(SHF_MERGE))
1406 .Case(CASE_ENT(SHF_STRINGS))
1407 .Case(CASE_ENT(SHF_INFO_LINK))
1408 .Case(CASE_ENT(SHF_LINK_ORDER))
1409 .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1410 .Case(CASE_ENT(SHF_GROUP))
1411 .Case(CASE_ENT(SHF_TLS))
1412 .Case(CASE_ENT(SHF_COMPRESSED))
1413 .Case(CASE_ENT(SHF_EXCLUDE))
1414 .Case(CASE_ENT(SHF_ARM_PURECODE))
1415 .Case(CASE_ENT(SHF_AARCH64_PURECODE))
1416 .Default(Value: std::nullopt);
1417#undef CASE_ENT
1418}
1419
1420// Reads the '(' <flags> ')' list of section flags in
1421// INPUT_SECTION_FLAGS '(' <flags> ')' in the
1422// following form:
1423// <flags> ::= <flag>
1424// | <flags> & flag
1425// <flag> ::= Recognized Flag Name, or Integer value of flag.
1426// If the first character of <flag> is a ! then this means without flag,
1427// otherwise with flag.
1428// Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1429// without flag SHF_WRITE.
1430std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1431 uint64_t withFlags = 0;
1432 uint64_t withoutFlags = 0;
1433 expect(expect: "(");
1434 while (!errCount(ctx)) {
1435 StringRef tok = readName();
1436 bool without = tok.consume_front(Prefix: "!");
1437 if (std::optional<uint64_t> flag = parseFlag(tok)) {
1438 if (without)
1439 withoutFlags |= *flag;
1440 else
1441 withFlags |= *flag;
1442 } else {
1443 setError("unrecognised flag: " + tok);
1444 }
1445 if (consume(tok: ")"))
1446 break;
1447 if (!consume(tok: "&")) {
1448 next();
1449 setError("expected & or )");
1450 }
1451 }
1452 return std::make_pair(x&: withFlags, y&: withoutFlags);
1453}
1454
1455StringRef ScriptParser::readParenName() {
1456 expect(expect: "(");
1457 auto saved = std::exchange(obj&: lexState, new_val: State::Script);
1458 StringRef name = readName();
1459 lexState = saved;
1460 expect(expect: ")");
1461 return name;
1462}
1463
1464static void checkIfExists(LinkerScript &script, const OutputSection &osec,
1465 StringRef location) {
1466 if (osec.location.empty() && script.errorOnMissingSection)
1467 script.recordError(msg: location + ": undefined section " + osec.name);
1468}
1469
1470static bool isValidSymbolName(StringRef s) {
1471 auto valid = [](char c) {
1472 return isAlnum(C: c) || c == '$' || c == '.' || c == '_';
1473 };
1474 return !s.empty() && !isDigit(C: s[0]) && llvm::all_of(Range&: s, P: valid);
1475}
1476
1477Expr ScriptParser::readPrimary() {
1478 if (peek() == "(")
1479 return readParenExpr();
1480
1481 if (consume(tok: "~")) {
1482 Expr e = readPrimary();
1483 return [=] { return ~e().getValue(); };
1484 }
1485 if (consume(tok: "!")) {
1486 Expr e = readPrimary();
1487 return [=] { return !e().getValue(); };
1488 }
1489 if (consume(tok: "-")) {
1490 Expr e = readPrimary();
1491 return [=] { return -e().getValue(); };
1492 }
1493 if (consume(tok: "+"))
1494 return readPrimary();
1495
1496 StringRef tok = next();
1497 std::string location = getCurrentLocation();
1498
1499 // Built-in functions are parsed here.
1500 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1501 if (tok == "ABSOLUTE") {
1502 Expr inner = readParenExpr();
1503 return [=] {
1504 ExprValue i = inner();
1505 i.forceAbsolute = true;
1506 return i;
1507 };
1508 }
1509 if (tok == "ADDR") {
1510 StringRef name = readParenName();
1511 OutputSection *osec = &ctx.script->getOrCreateOutputSection(name)->osec;
1512 osec->usedInExpression = true;
1513 return [=, s = ctx.script]() -> ExprValue {
1514 checkIfExists(script&: *s, osec: *osec, location);
1515 return {osec, false, 0, location};
1516 };
1517 }
1518 if (tok == "ALIGN") {
1519 expect(expect: "(");
1520 Expr e = readExpr();
1521 if (consume(tok: ")")) {
1522 e = checkAlignment(ctx, e, loc&: location);
1523 return [=, s = ctx.script] {
1524 return alignToPowerOf2(Value: s->getDot(), Align: e().getValue());
1525 };
1526 }
1527 expect(expect: ",");
1528 Expr e2 = checkAlignment(ctx, e: readExpr(), loc&: location);
1529 expect(expect: ")");
1530 return [=] {
1531 ExprValue v = e();
1532 v.alignment = e2().getValue();
1533 return v;
1534 };
1535 }
1536 if (tok == "ALIGNOF") {
1537 StringRef name = readParenName();
1538 OutputSection *osec = &ctx.script->getOrCreateOutputSection(name)->osec;
1539 return [=, s = ctx.script] {
1540 checkIfExists(script&: *s, osec: *osec, location);
1541 return osec->addralign;
1542 };
1543 }
1544 if (tok == "ASSERT")
1545 return readAssert();
1546 if (tok == "CONSTANT")
1547 return readConstant();
1548 if (tok == "DATA_SEGMENT_ALIGN") {
1549 expect(expect: "(");
1550 Expr e = readExpr();
1551 expect(expect: ",");
1552 readExpr();
1553 expect(expect: ")");
1554 ctx.script->seenDataAlign = true;
1555 return [=, s = ctx.script] {
1556 uint64_t align = std::max(a: uint64_t(1), b: e().getValue());
1557 return (s->getDot() + align - 1) & -align;
1558 };
1559 }
1560 if (tok == "DATA_SEGMENT_END") {
1561 expect(expect: "(");
1562 expect(expect: ".");
1563 expect(expect: ")");
1564 return [s = ctx.script] { return s->getDot(); };
1565 }
1566 if (tok == "DATA_SEGMENT_RELRO_END") {
1567 // GNU linkers implements more complicated logic to handle
1568 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1569 // just align to the next page boundary for simplicity.
1570 expect(expect: "(");
1571 readExpr();
1572 expect(expect: ",");
1573 readExpr();
1574 expect(expect: ")");
1575 ctx.script->seenRelroEnd = true;
1576 return [&ctx = this->ctx] {
1577 return alignToPowerOf2(Value: ctx.script->getDot(), Align: ctx.arg.maxPageSize);
1578 };
1579 }
1580 if (tok == "DEFINED") {
1581 StringRef name = readParenName();
1582 // Return 1 if s is defined. If the definition is only found in a linker
1583 // script, it must happen before this DEFINED.
1584 auto order = ctx.scriptSymOrderCounter++;
1585 return [=, &ctx = this->ctx] {
1586 Symbol *s = ctx.symtab->find(name);
1587 return s && s->isDefined() && ctx.scriptSymOrder.lookup(Val: s) < order ? 1
1588 : 0;
1589 };
1590 }
1591 if (tok == "LENGTH") {
1592 StringRef name = readParenName();
1593 if (!ctx.script->memoryRegions.contains(Key: name)) {
1594 setError("memory region not defined: " + name);
1595 return [] { return 0; };
1596 }
1597 return ctx.script->memoryRegions[name]->length;
1598 }
1599 if (tok == "LOADADDR") {
1600 StringRef name = readParenName();
1601 OutputSection *osec = &ctx.script->getOrCreateOutputSection(name)->osec;
1602 osec->usedInExpression = true;
1603 return [=, s = ctx.script] {
1604 checkIfExists(script&: *s, osec: *osec, location);
1605 return osec->getLMA();
1606 };
1607 }
1608 if (tok == "LOG2CEIL") {
1609 expect(expect: "(");
1610 Expr a = readExpr();
1611 expect(expect: ")");
1612 return [=] {
1613 // LOG2CEIL(0) is defined to be 0.
1614 return llvm::Log2_64_Ceil(Value: std::max(a: a().getValue(), UINT64_C(1)));
1615 };
1616 }
1617 if (tok == "MAX" || tok == "MIN") {
1618 expect(expect: "(");
1619 Expr a = readExpr();
1620 expect(expect: ",");
1621 Expr b = readExpr();
1622 expect(expect: ")");
1623 if (tok == "MIN")
1624 return [=] { return std::min(a: a().getValue(), b: b().getValue()); };
1625 return [=] { return std::max(a: a().getValue(), b: b().getValue()); };
1626 }
1627 if (tok == "ORIGIN") {
1628 StringRef name = readParenName();
1629 if (!ctx.script->memoryRegions.contains(Key: name)) {
1630 setError("memory region not defined: " + name);
1631 return [] { return 0; };
1632 }
1633 return ctx.script->memoryRegions[name]->origin;
1634 }
1635 if (tok == "SEGMENT_START") {
1636 expect(expect: "(");
1637 skip();
1638 expect(expect: ",");
1639 Expr e = readExpr();
1640 expect(expect: ")");
1641 return [=] { return e(); };
1642 }
1643 if (tok == "SIZEOF") {
1644 StringRef name = readParenName();
1645 OutputSection *cmd = &ctx.script->getOrCreateOutputSection(name)->osec;
1646 // Linker script does not create an output section if its content is empty.
1647 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1648 // be empty.
1649 return [=] { return cmd->size; };
1650 }
1651 if (tok == "SIZEOF_HEADERS")
1652 return [=, &ctx = ctx] { return elf::getHeaderSize(ctx); };
1653
1654 // Tok is the dot.
1655 if (tok == ".")
1656 return [=, s = ctx.script] { return s->getSymbolValue(name: tok, loc: location); };
1657
1658 // Tok is a literal number.
1659 if (std::optional<uint64_t> val = parseInt(tok))
1660 return [=] { return *val; };
1661
1662 // Tok is a symbol name.
1663 if (tok.starts_with(Prefix: "\""))
1664 tok = unquote(s: tok);
1665 else if (!isValidSymbolName(s: tok))
1666 setError("malformed number: " + tok);
1667 if (activeProvideSym)
1668 ctx.script->provideMap[*activeProvideSym].push_back(Elt: tok);
1669 else
1670 ctx.script->referencedSymbols.push_back(Elt: tok);
1671 return [=, s = ctx.script] { return s->getSymbolValue(name: tok, loc: location); };
1672}
1673
1674Expr ScriptParser::readTernary(Expr cond) {
1675 Expr l = readExpr();
1676 expect(expect: ":");
1677 Expr r = readExpr();
1678 return [=] { return cond().getValue() ? l() : r(); };
1679}
1680
1681Expr ScriptParser::readParenExpr() {
1682 expect(expect: "(");
1683 Expr e = readExpr();
1684 expect(expect: ")");
1685 return e;
1686}
1687
1688SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {
1689 SmallVector<StringRef, 0> phdrs;
1690 while (!errCount(ctx) && peek().starts_with(Prefix: ":")) {
1691 StringRef tok = next();
1692 phdrs.push_back(Elt: (tok.size() == 1) ? readName() : tok.substr(Start: 1));
1693 }
1694 return phdrs;
1695}
1696
1697// Read a program header type name. The next token must be a
1698// name of a program header type or a constant (e.g. "0x3").
1699unsigned ScriptParser::readPhdrType() {
1700 StringRef tok = next();
1701 if (std::optional<uint64_t> val = parseInt(tok))
1702 return *val;
1703
1704 unsigned ret = StringSwitch<unsigned>(tok)
1705 .Case(S: "PT_NULL", Value: PT_NULL)
1706 .Case(S: "PT_LOAD", Value: PT_LOAD)
1707 .Case(S: "PT_DYNAMIC", Value: PT_DYNAMIC)
1708 .Case(S: "PT_INTERP", Value: PT_INTERP)
1709 .Case(S: "PT_NOTE", Value: PT_NOTE)
1710 .Case(S: "PT_SHLIB", Value: PT_SHLIB)
1711 .Case(S: "PT_PHDR", Value: PT_PHDR)
1712 .Case(S: "PT_TLS", Value: PT_TLS)
1713 .Case(S: "PT_GNU_EH_FRAME", Value: PT_GNU_EH_FRAME)
1714 .Case(S: "PT_GNU_STACK", Value: PT_GNU_STACK)
1715 .Case(S: "PT_GNU_RELRO", Value: PT_GNU_RELRO)
1716 .Case(S: "PT_OPENBSD_MUTABLE", Value: PT_OPENBSD_MUTABLE)
1717 .Case(S: "PT_OPENBSD_RANDOMIZE", Value: PT_OPENBSD_RANDOMIZE)
1718 .Case(S: "PT_OPENBSD_SYSCALLS", Value: PT_OPENBSD_SYSCALLS)
1719 .Case(S: "PT_OPENBSD_WXNEEDED", Value: PT_OPENBSD_WXNEEDED)
1720 .Case(S: "PT_OPENBSD_BOOTDATA", Value: PT_OPENBSD_BOOTDATA)
1721 .Default(Value: -1);
1722
1723 if (ret == (unsigned)-1) {
1724 setError("invalid program header type: " + tok);
1725 return PT_NULL;
1726 }
1727 return ret;
1728}
1729
1730// Reads an anonymous version declaration.
1731void ScriptParser::readAnonymousDeclaration() {
1732 SmallVector<SymbolVersion, 0> locals;
1733 SmallVector<SymbolVersion, 0> globals;
1734 std::tie(args&: locals, args&: globals) = readSymbols();
1735 for (const SymbolVersion &pat : locals)
1736 ctx.arg.versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(Elt: pat);
1737 for (const SymbolVersion &pat : globals)
1738 ctx.arg.versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(Elt: pat);
1739
1740 expect(expect: ";");
1741}
1742
1743// Reads a non-anonymous version definition,
1744// e.g. "VerStr { global: foo; bar; local: *; };".
1745void ScriptParser::readVersionDeclaration(StringRef verStr) {
1746 // Read a symbol list.
1747 SmallVector<SymbolVersion, 0> locals;
1748 SmallVector<SymbolVersion, 0> globals;
1749 std::tie(args&: locals, args&: globals) = readSymbols();
1750
1751 // Create a new version definition and add that to the global symbols.
1752 VersionDefinition ver;
1753 ver.name = verStr;
1754 ver.nonLocalPatterns = std::move(globals);
1755 ver.localPatterns = std::move(locals);
1756 ver.id = ctx.arg.versionDefinitions.size();
1757 ctx.arg.versionDefinitions.push_back(Elt: ver);
1758
1759 // Each version may have a parent version. For example, "Ver2"
1760 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1761 // as a parent. This version hierarchy is, probably against your
1762 // instinct, purely for hint; the runtime doesn't care about it
1763 // at all. In LLD, we simply ignore it.
1764 if (next() != ";")
1765 expect(expect: ";");
1766}
1767
1768bool elf::hasWildcard(StringRef s) {
1769 return s.find_first_of(Chars: "?*[") != StringRef::npos;
1770}
1771
1772// Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1773std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
1774ScriptParser::readSymbols() {
1775 SmallVector<SymbolVersion, 0> locals;
1776 SmallVector<SymbolVersion, 0> globals;
1777 SmallVector<SymbolVersion, 0> *v = &globals;
1778
1779 while (auto tok = till(tok: "}")) {
1780 if (tok == "extern") {
1781 SmallVector<SymbolVersion, 0> ext = readVersionExtern();
1782 v->insert(I: v->end(), From: ext.begin(), To: ext.end());
1783 } else {
1784 if (tok == "local" && consume(tok: ":")) {
1785 v = &locals;
1786 continue;
1787 }
1788 if (tok == "global" && consume(tok: ":")) {
1789 v = &globals;
1790 continue;
1791 }
1792 v->push_back(Elt: {.name: unquote(s: tok), .isExternCpp: false, .hasWildcard: hasWildcard(s: tok)});
1793 }
1794 expect(expect: ";");
1795 }
1796 return {locals, globals};
1797}
1798
1799// Reads an "extern C++" directive, e.g.,
1800// "extern "C++" { ns::*; "f(int, double)"; };"
1801//
1802// The last semicolon is optional. E.g. this is OK:
1803// "extern "C++" { ns::*; "f(int, double)" };"
1804SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {
1805 StringRef tok = next();
1806 bool isCXX = tok == "\"C++\"";
1807 if (!isCXX && tok != "\"C\"")
1808 setError("Unknown language");
1809 expect(expect: "{");
1810
1811 SmallVector<SymbolVersion, 0> ret;
1812 while (auto tok = till(tok: "}")) {
1813 ret.push_back(
1814 Elt: {.name: unquote(s: tok), .isExternCpp: isCXX, .hasWildcard: !tok.str.starts_with(Prefix: "\"") && hasWildcard(s: tok)});
1815 if (consume(tok: "}"))
1816 return ret;
1817 expect(expect: ";");
1818 }
1819 return ret;
1820}
1821
1822Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
1823 StringRef s3) {
1824 if (!consume(tok: s1) && !consume(tok: s2) && !consume(tok: s3)) {
1825 setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
1826 return [] { return 0; };
1827 }
1828 expect(expect: "=");
1829 return readExpr();
1830}
1831
1832// Parse the MEMORY command as specified in:
1833// https://sourceware.org/binutils/docs/ld/MEMORY.html
1834//
1835// MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1836void ScriptParser::readMemory() {
1837 expect(expect: "{");
1838 while (auto tok = till(tok: "}")) {
1839 if (tok == "INCLUDE") {
1840 readInclude();
1841 continue;
1842 }
1843
1844 uint32_t flags = 0;
1845 uint32_t invFlags = 0;
1846 uint32_t negFlags = 0;
1847 uint32_t negInvFlags = 0;
1848 if (consume(tok: "(")) {
1849 readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);
1850 expect(expect: ")");
1851 }
1852 expect(expect: ":");
1853
1854 Expr origin = readMemoryAssignment(s1: "ORIGIN", s2: "org", s3: "o");
1855 expect(expect: ",");
1856 Expr length = readMemoryAssignment(s1: "LENGTH", s2: "len", s3: "l");
1857
1858 // Add the memory region to the region map.
1859 MemoryRegion *mr = make<MemoryRegion>(args&: tok, args&: origin, args&: length, args&: flags, args&: invFlags,
1860 args&: negFlags, args&: negInvFlags);
1861 if (!ctx.script->memoryRegions.insert(KV: {tok, mr}).second)
1862 setError("region '" + tok + "' already defined");
1863 }
1864}
1865
1866// This function parses the attributes used to match against section
1867// flags when placing output sections in a memory region. These flags
1868// are only used when an explicit memory region name is not used.
1869void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
1870 uint32_t &negFlags,
1871 uint32_t &negInvFlags) {
1872 bool invert = false;
1873
1874 for (char c : next().lower()) {
1875 if (c == '!') {
1876 invert = !invert;
1877 std::swap(a&: flags, b&: negFlags);
1878 std::swap(a&: invFlags, b&: negInvFlags);
1879 continue;
1880 }
1881 if (c == 'w')
1882 flags |= SHF_WRITE;
1883 else if (c == 'x')
1884 flags |= SHF_EXECINSTR;
1885 else if (c == 'a')
1886 flags |= SHF_ALLOC;
1887 else if (c == 'r')
1888 invFlags |= SHF_WRITE;
1889 else
1890 setError("invalid memory region attribute");
1891 }
1892
1893 if (invert) {
1894 std::swap(a&: flags, b&: negFlags);
1895 std::swap(a&: invFlags, b&: negInvFlags);
1896 }
1897}
1898
1899void elf::readLinkerScript(Ctx &ctx, MemoryBufferRef mb) {
1900 llvm::TimeTraceScope timeScope("Read linker script",
1901 mb.getBufferIdentifier());
1902 ScriptParser(ctx, mb).readLinkerScript();
1903}
1904
1905void elf::readVersionScript(Ctx &ctx, MemoryBufferRef mb) {
1906 llvm::TimeTraceScope timeScope("Read version script",
1907 mb.getBufferIdentifier());
1908 ScriptParser(ctx, mb).readVersionScript();
1909}
1910
1911void elf::readDynamicList(Ctx &ctx, MemoryBufferRef mb) {
1912 llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
1913 ScriptParser(ctx, mb).readDynamicList();
1914}
1915
1916void elf::readDefsym(Ctx &ctx, MemoryBufferRef mb) {
1917 ScriptParser(ctx, mb).readDefsym();
1918}
1919