1 //===- ScriptParser.cpp ---------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains a recursive-descendent parser for linker scripts.
10 // Parsed results are stored to Config and Script global objects.
12 //===----------------------------------------------------------------------===//
14 #include "ScriptParser.h"
17 #include "InputFiles.h"
18 #include "LinkerScript.h"
19 #include "OutputSections.h"
20 #include "ScriptLexer.h"
21 #include "SymbolTable.h"
24 #include "lld/Common/CommonLinkerContext.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/SaveAndRestore.h"
35 #include "llvm/Support/TimeProfiler.h"
42 using namespace llvm::ELF
;
43 using namespace llvm::support::endian
;
45 using namespace lld::elf
;
48 class ScriptParser final
: ScriptLexer
{
50 ScriptParser(Ctx
&ctx
, MemoryBufferRef mb
) : ScriptLexer(ctx
, mb
), ctx(ctx
) {}
52 void readLinkerScript();
53 void readVersionScript();
54 void readDynamicList();
58 void addFile(StringRef path
);
68 void readOutputArch();
69 void readOutputFormat();
70 void readOverwriteSections();
72 void readRegionAlias();
77 void readVersionScriptCommand();
78 void readNoCrossRefs(bool to
);
81 SymbolAssignment
*readSymbolAssignment(StringRef name
);
82 ByteCommand
*readByteCommand(StringRef tok
);
83 std::array
<uint8_t, 4> readFill();
84 bool readSectionDirective(OutputSection
*cmd
, StringRef tok
);
85 void readSectionAddressType(OutputSection
*cmd
);
86 OutputDesc
*readOverlaySectionDescription();
87 OutputDesc
*readOutputSectionDescription(StringRef outSec
);
88 SmallVector
<SectionCommand
*, 0> readOverlay();
89 SectionClassDesc
*readSectionClassDescription();
90 StringRef
readSectionClassName();
91 SmallVector
<StringRef
, 0> readOutputSectionPhdrs();
92 std::pair
<uint64_t, uint64_t> readInputSectionFlags();
93 InputSectionDescription
*readInputSectionDescription(StringRef tok
);
94 StringMatcher
readFilePatterns();
95 SmallVector
<SectionPattern
, 0> readInputSectionsList();
96 InputSectionDescription
*readInputSectionRules(StringRef filePattern
,
98 uint64_t withoutFlags
);
99 unsigned readPhdrType();
100 SortSectionPolicy
peekSortKind();
101 SortSectionPolicy
readSortKind();
102 SymbolAssignment
*readProvideHidden(bool provide
, bool hidden
);
103 SymbolAssignment
*readAssignment(StringRef tok
);
109 Expr
readMemoryAssignment(StringRef
, StringRef
, StringRef
);
110 void readMemoryAttributes(uint32_t &flags
, uint32_t &invFlags
,
111 uint32_t &negFlags
, uint32_t &negInvFlags
);
113 Expr
combine(StringRef op
, Expr l
, Expr r
);
115 Expr
readExpr1(Expr lhs
, int minPrec
);
116 StringRef
readParenName();
118 Expr
readTernary(Expr cond
);
119 Expr
readParenExpr();
121 // For parsing version script.
122 SmallVector
<SymbolVersion
, 0> readVersionExtern();
123 void readAnonymousDeclaration();
124 void readVersionDeclaration(StringRef verStr
);
126 std::pair
<SmallVector
<SymbolVersion
, 0>, SmallVector
<SymbolVersion
, 0>>
131 // If we are currently parsing a PROVIDE|PROVIDE_HIDDEN command,
132 // then this member is set to the PROVIDE symbol name.
133 std::optional
<llvm::StringRef
> activeProvideSym
;
137 static StringRef
unquote(StringRef s
) {
138 if (s
.starts_with("\""))
139 return s
.substr(1, s
.size() - 2);
143 // Some operations only support one non absolute value. Move the
144 // absolute one to the right hand side for convenience.
145 static void moveAbsRight(LinkerScript
&s
, ExprValue
&a
, ExprValue
&b
) {
146 if (a
.sec
== nullptr || (a
.forceAbsolute
&& !b
.isAbsolute()))
149 s
.recordError(a
.loc
+
150 ": at least one side of the expression must be absolute");
153 static ExprValue
add(LinkerScript
&s
, ExprValue a
, ExprValue b
) {
154 moveAbsRight(s
, a
, b
);
155 return {a
.sec
, a
.forceAbsolute
, a
.getSectionOffset() + b
.getValue(), a
.loc
};
158 static ExprValue
sub(ExprValue a
, ExprValue b
) {
159 // The distance between two symbols in sections is absolute.
160 if (!a
.isAbsolute() && !b
.isAbsolute())
161 return a
.getValue() - b
.getValue();
162 return {a
.sec
, false, a
.getSectionOffset() - b
.getValue(), a
.loc
};
165 static ExprValue
bitAnd(LinkerScript
&s
, ExprValue a
, ExprValue b
) {
166 moveAbsRight(s
, a
, b
);
167 return {a
.sec
, a
.forceAbsolute
,
168 (a
.getValue() & b
.getValue()) - a
.getSecAddr(), a
.loc
};
171 static ExprValue
bitXor(LinkerScript
&s
, ExprValue a
, ExprValue b
) {
172 moveAbsRight(s
, a
, b
);
173 return {a
.sec
, a
.forceAbsolute
,
174 (a
.getValue() ^ b
.getValue()) - a
.getSecAddr(), a
.loc
};
177 static ExprValue
bitOr(LinkerScript
&s
, ExprValue a
, ExprValue b
) {
178 moveAbsRight(s
, a
, b
);
179 return {a
.sec
, a
.forceAbsolute
,
180 (a
.getValue() | b
.getValue()) - a
.getSecAddr(), a
.loc
};
183 void ScriptParser::readDynamicList() {
185 SmallVector
<SymbolVersion
, 0> locals
;
186 SmallVector
<SymbolVersion
, 0> globals
;
187 std::tie(locals
, globals
) = readSymbols();
190 StringRef tok
= peek();
192 setError("EOF expected, but got " + tok
);
195 if (!locals
.empty()) {
196 setError("\"local:\" scope not supported in --dynamic-list");
200 for (SymbolVersion v
: globals
)
201 ctx
.arg
.dynamicList
.push_back(v
);
204 void ScriptParser::readVersionScript() {
205 readVersionScriptCommand();
206 StringRef tok
= peek();
208 setError("EOF expected, but got " + tok
);
211 void ScriptParser::readVersionScriptCommand() {
213 readAnonymousDeclaration();
218 setError("unexpected EOF");
219 while (peek() != "}" && !atEOF()) {
220 StringRef verStr
= next();
222 setError("anonymous version definition is used in "
223 "combination with other version definitions");
227 readVersionDeclaration(verStr
);
231 void ScriptParser::readVersion() {
233 readVersionScriptCommand();
237 void ScriptParser::readLinkerScript() {
239 StringRef tok
= next();
245 if (tok
== "ENTRY") {
247 } else if (tok
== "EXTERN") {
249 } else if (tok
== "GROUP") {
251 } else if (tok
== "INCLUDE") {
253 } else if (tok
== "INPUT") {
255 } else if (tok
== "MEMORY") {
257 } else if (tok
== "OUTPUT") {
259 } else if (tok
== "OUTPUT_ARCH") {
261 } else if (tok
== "OUTPUT_FORMAT") {
263 } else if (tok
== "OVERWRITE_SECTIONS") {
264 readOverwriteSections();
265 } else if (tok
== "PHDRS") {
267 } else if (tok
== "REGION_ALIAS") {
269 } else if (tok
== "SEARCH_DIR") {
271 } else if (tok
== "SECTIONS") {
273 } else if (tok
== "TARGET") {
275 } else if (tok
== "VERSION") {
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(cmd
);
284 setError("unknown directive: " + tok
);
289 void ScriptParser::readDefsym() {
293 StringRef name
= readName();
297 setError("EOF expected, but got " + next());
298 auto *cmd
= make
<SymbolAssignment
>(
299 name
, e
, 0, getCurrentMB().getBufferIdentifier().str());
300 ctx
.script
->sectionCommands
.push_back(cmd
);
303 void ScriptParser::readNoCrossRefs(bool to
) {
305 NoCrossRefCommand cmd
{{}, to
};
306 while (auto tok
= till(")"))
307 cmd
.outputSections
.push_back(unquote(tok
));
308 if (cmd
.outputSections
.size() < 2)
309 Warn(ctx
) << getCurrentLocation()
310 << ": ignored with fewer than 2 output sections";
312 ctx
.script
->noCrossRefs
.push_back(std::move(cmd
));
315 void ScriptParser::addFile(StringRef s
) {
316 if (curBuf
.isUnderSysroot
&& s
.starts_with("/")) {
317 SmallString
<128> pathData
;
318 StringRef path
= (ctx
.arg
.sysroot
+ s
).toStringRef(pathData
);
319 if (sys::fs::exists(path
))
320 ctx
.driver
.addFile(ctx
.saver
.save(path
), /*withLOption=*/false);
322 setError("cannot find " + s
+ " inside " + ctx
.arg
.sysroot
);
326 if (s
.starts_with("/")) {
327 // Case 1: s is an absolute path. Just open it.
328 ctx
.driver
.addFile(s
, /*withLOption=*/false);
329 } else if (s
.starts_with("=")) {
330 // Case 2: relative to the sysroot.
331 if (ctx
.arg
.sysroot
.empty())
332 ctx
.driver
.addFile(s
.substr(1), /*withLOption=*/false);
334 ctx
.driver
.addFile(ctx
.saver
.save(ctx
.arg
.sysroot
+ "/" + s
.substr(1)),
335 /*withLOption=*/false);
336 } else if (s
.starts_with("-l")) {
337 // Case 3: search in the list of library paths.
338 ctx
.driver
.addLibrary(s
.substr(2));
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(filename
);
343 if (!directory
.empty()) {
344 SmallString
<0> path(directory
);
345 sys::path::append(path
, s
);
346 if (sys::fs::exists(path
)) {
347 ctx
.driver
.addFile(path
, /*withLOption=*/false);
351 // Then search in the current working directory.
352 if (sys::fs::exists(s
)) {
353 ctx
.driver
.addFile(s
, /*withLOption=*/false);
355 // Finally, search in the list of library paths.
356 if (std::optional
<std::string
> path
= findFromSearchPaths(ctx
, s
))
357 ctx
.driver
.addFile(ctx
.saver
.save(*path
), /*withLOption=*/true);
359 setError("unable to find " + s
);
364 void ScriptParser::readAsNeeded() {
366 bool orig
= ctx
.arg
.asNeeded
;
367 ctx
.arg
.asNeeded
= true;
368 while (auto tok
= till(")"))
369 addFile(unquote(tok
));
370 ctx
.arg
.asNeeded
= orig
;
373 void ScriptParser::readEntry() {
374 // -e <symbol> takes predecence over ENTRY(<symbol>).
376 StringRef name
= readName();
377 if (ctx
.arg
.entry
.empty())
378 ctx
.arg
.entry
= name
;
382 void ScriptParser::readExtern() {
384 while (auto tok
= till(")"))
385 ctx
.arg
.undefined
.push_back(unquote(tok
));
388 void ScriptParser::readGroup() {
389 SaveAndRestore
saved(ctx
.driver
.isInGroup
, true);
392 ++ctx
.driver
.nextGroupId
;
395 void ScriptParser::readInclude() {
396 StringRef name
= readName();
397 if (!activeFilenames
.insert(name
).second
) {
398 setError("there is a cycle in linker script INCLUDEs");
402 if (std::optional
<std::string
> path
= searchScript(ctx
, name
)) {
403 if (std::optional
<MemoryBufferRef
> mb
= readFile(ctx
, *path
)) {
404 buffers
.push_back(curBuf
);
405 curBuf
= Buffer(ctx
, *mb
);
410 setError("cannot find linker script " + name
);
413 void ScriptParser::readInput() {
415 while (auto tok
= till(")")) {
416 if (tok
== "AS_NEEDED")
419 addFile(unquote(tok
));
423 void ScriptParser::readOutput() {
424 // -o <file> takes predecence over OUTPUT(<file>).
426 StringRef name
= readName();
427 if (ctx
.arg
.outputFile
.empty())
428 ctx
.arg
.outputFile
= name
;
432 void ScriptParser::readOutputArch() {
433 // OUTPUT_ARCH is ignored for now.
439 static std::pair
<ELFKind
, uint16_t> parseBfdName(StringRef s
) {
440 return StringSwitch
<std::pair
<ELFKind
, uint16_t>>(s
)
441 .Case("elf32-i386", {ELF32LEKind
, EM_386
})
442 .Case("elf32-avr", {ELF32LEKind
, EM_AVR
})
443 .Case("elf32-iamcu", {ELF32LEKind
, EM_IAMCU
})
444 .Case("elf32-littlearm", {ELF32LEKind
, EM_ARM
})
445 .Case("elf32-bigarm", {ELF32BEKind
, EM_ARM
})
446 .Case("elf32-x86-64", {ELF32LEKind
, EM_X86_64
})
447 .Case("elf64-aarch64", {ELF64LEKind
, EM_AARCH64
})
448 .Case("elf64-littleaarch64", {ELF64LEKind
, EM_AARCH64
})
449 .Case("elf64-bigaarch64", {ELF64BEKind
, EM_AARCH64
})
450 .Case("elf32-powerpc", {ELF32BEKind
, EM_PPC
})
451 .Case("elf32-powerpcle", {ELF32LEKind
, EM_PPC
})
452 .Case("elf64-powerpc", {ELF64BEKind
, EM_PPC64
})
453 .Case("elf64-powerpcle", {ELF64LEKind
, EM_PPC64
})
454 .Case("elf64-x86-64", {ELF64LEKind
, EM_X86_64
})
455 .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind
, EM_MIPS
})
456 .Case("elf32-ntradbigmips", {ELF32BEKind
, EM_MIPS
})
457 .Case("elf32-tradlittlemips", {ELF32LEKind
, EM_MIPS
})
458 .Case("elf32-ntradlittlemips", {ELF32LEKind
, EM_MIPS
})
459 .Case("elf64-tradbigmips", {ELF64BEKind
, EM_MIPS
})
460 .Case("elf64-tradlittlemips", {ELF64LEKind
, EM_MIPS
})
461 .Case("elf32-littleriscv", {ELF32LEKind
, EM_RISCV
})
462 .Case("elf64-littleriscv", {ELF64LEKind
, EM_RISCV
})
463 .Case("elf64-sparc", {ELF64BEKind
, EM_SPARCV9
})
464 .Case("elf32-msp430", {ELF32LEKind
, EM_MSP430
})
465 .Case("elf32-loongarch", {ELF32LEKind
, EM_LOONGARCH
})
466 .Case("elf64-loongarch", {ELF64LEKind
, EM_LOONGARCH
})
467 .Case("elf64-s390", {ELF64BEKind
, EM_S390
})
468 .Cases("elf32-hexagon", "elf32-littlehexagon", {ELF32LEKind
, EM_HEXAGON
})
469 .Default({ELFNoneKind
, EM_NONE
});
472 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
473 // big if -EB is specified, little if -EL is specified, or default if neither is
475 void ScriptParser::readOutputFormat() {
478 StringRef s
= readName();
481 StringRef tmp
= readName();
490 // If more than one OUTPUT_FORMAT is specified, only the first is checked.
491 if (!ctx
.arg
.bfdname
.empty())
496 ctx
.arg
.oFormatBinary
= true;
500 if (s
.consume_back("-freebsd"))
501 ctx
.arg
.osabi
= ELFOSABI_FREEBSD
;
503 std::tie(ctx
.arg
.ekind
, ctx
.arg
.emachine
) = parseBfdName(s
);
504 if (ctx
.arg
.emachine
== EM_NONE
)
505 setError("unknown output format name: " + ctx
.arg
.bfdname
);
506 if (s
== "elf32-ntradlittlemips" || s
== "elf32-ntradbigmips")
507 ctx
.arg
.mipsN32Abi
= true;
508 if (ctx
.arg
.emachine
== EM_MSP430
)
509 ctx
.arg
.osabi
= ELFOSABI_STANDALONE
;
512 void ScriptParser::readPhdrs() {
514 while (auto tok
= till("}")) {
517 cmd
.type
= readPhdrType();
519 while (!errCount(ctx
) && !consume(";")) {
520 if (consume("FILEHDR"))
521 cmd
.hasFilehdr
= true;
522 else if (consume("PHDRS"))
524 else if (consume("AT"))
525 cmd
.lmaExpr
= readParenExpr();
526 else if (consume("FLAGS"))
527 cmd
.flags
= readParenExpr()().getValue();
529 setError("unexpected header attribute: " + next());
532 ctx
.script
->phdrsCommands
.push_back(cmd
);
536 void ScriptParser::readRegionAlias() {
538 StringRef alias
= readName();
540 StringRef name
= readName();
543 if (ctx
.script
->memoryRegions
.count(alias
))
544 setError("redefinition of memory region '" + alias
+ "'");
545 if (!ctx
.script
->memoryRegions
.count(name
))
546 setError("memory region '" + name
+ "' is not defined");
547 ctx
.script
->memoryRegions
.insert({alias
, ctx
.script
->memoryRegions
[name
]});
550 void ScriptParser::readSearchDir() {
552 StringRef name
= readName();
553 if (!ctx
.arg
.nostdlib
)
554 ctx
.arg
.searchPaths
.push_back(name
);
558 // This reads an overlay description. Overlays are used to describe output
559 // sections that use the same virtual memory range and normally would trigger
560 // linker's sections sanity check failures.
561 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
562 SmallVector
<SectionCommand
*, 0> ScriptParser::readOverlay() {
565 addrExpr
= [s
= ctx
.script
] { return s
->getDot(); };
567 addrExpr
= readExpr();
570 // When AT is omitted, LMA should equal VMA. script->getDot() when evaluating
571 // lmaExpr will ensure this, even if the start address is specified.
572 Expr lmaExpr
= consume("AT") ? readParenExpr()
573 : [s
= ctx
.script
] { return s
->getDot(); };
576 SmallVector
<SectionCommand
*, 0> v
;
577 OutputSection
*prev
= nullptr;
578 while (!errCount(ctx
) && !consume("}")) {
579 // VA is the same for all sections. The LMAs are consecutive in memory
580 // starting from the base load address specified.
581 OutputDesc
*osd
= readOverlaySectionDescription();
582 osd
->osec
.addrExpr
= addrExpr
;
584 osd
->osec
.lmaExpr
= [=] { return prev
->getLMA() + prev
->size
; };
586 osd
->osec
.lmaExpr
= lmaExpr
;
587 // Use first section address for subsequent sections as initial addrExpr
588 // can be DOT. Ensure the first section, even if empty, is not discarded.
589 osd
->osec
.usedInExpression
= true;
590 addrExpr
= [=]() -> ExprValue
{ return {&osd
->osec
, false, 0, ""}; };
596 // According to the specification, at the end of the overlay, the location
597 // counter should be equal to the overlay base address plus size of the
598 // largest section seen in the overlay.
599 // Here we want to create the Dot assignment command to achieve that.
602 for (SectionCommand
*cmd
: v
)
603 max
= std::max(max
, cast
<OutputDesc
>(cmd
)->osec
.size
);
604 return addrExpr().getValue() + max
;
606 v
.push_back(make
<SymbolAssignment
>(".", moveDot
, 0, getCurrentLocation()));
610 SectionClassDesc
*ScriptParser::readSectionClassDescription() {
611 StringRef name
= readSectionClassName();
612 SectionClassDesc
*desc
= make
<SectionClassDesc
>(name
);
613 if (!ctx
.script
->sectionClasses
.insert({CachedHashStringRef(name
), desc
})
615 setError("section class '" + name
+ "' already defined");
617 while (auto tok
= till("}")) {
618 if (tok
== "(" || tok
== ")") {
619 setError("expected filename pattern");
620 } else if (peek() == "(") {
621 InputSectionDescription
*isd
= readInputSectionDescription(tok
);
622 if (!isd
->classRef
.empty())
623 setError("section class '" + name
+ "' references class '" +
624 isd
->classRef
+ "'");
625 desc
->sc
.commands
.push_back(isd
);
631 StringRef
ScriptParser::readSectionClassName() {
633 StringRef name
= unquote(next());
638 void ScriptParser::readOverwriteSections() {
640 while (auto tok
= till("}"))
641 ctx
.script
->overwriteSections
.push_back(readOutputSectionDescription(tok
));
644 void ScriptParser::readSections() {
646 SmallVector
<SectionCommand
*, 0> v
;
647 while (auto tok
= till("}")) {
648 if (tok
== "OVERLAY") {
649 for (SectionCommand
*cmd
: readOverlay())
653 if (tok
== "CLASS") {
654 v
.push_back(readSectionClassDescription());
657 if (tok
== "INCLUDE") {
662 if (SectionCommand
*cmd
= readAssignment(tok
))
665 v
.push_back(readOutputSectionDescription(tok
));
668 // If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN,
669 // the relro fields should be cleared.
670 if (!ctx
.script
->seenRelroEnd
)
671 for (SectionCommand
*cmd
: v
)
672 if (auto *osd
= dyn_cast
<OutputDesc
>(cmd
))
673 osd
->osec
.relro
= false;
675 ctx
.script
->sectionCommands
.insert(ctx
.script
->sectionCommands
.end(),
678 if (atEOF() || !consume("INSERT")) {
679 ctx
.script
->hasSectionsCommand
= true;
683 bool isAfter
= false;
684 if (consume("AFTER"))
686 else if (!consume("BEFORE"))
687 setError("expected AFTER/BEFORE, but got '" + next() + "'");
688 StringRef where
= readName();
689 SmallVector
<StringRef
, 0> names
;
690 for (SectionCommand
*cmd
: v
)
691 if (auto *os
= dyn_cast
<OutputDesc
>(cmd
))
692 names
.push_back(os
->osec
.name
);
694 ctx
.script
->insertCommands
.push_back({std::move(names
), isAfter
, where
});
697 void ScriptParser::readTarget() {
698 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
699 // we accept only a limited set of BFD names (i.e. "elf" or "binary")
700 // for --format. We recognize only /^elf/ and "binary" in the linker
703 StringRef tok
= readName();
706 if (tok
.starts_with("elf"))
707 ctx
.arg
.formatBinary
= false;
708 else if (tok
== "binary")
709 ctx
.arg
.formatBinary
= true;
711 setError("unknown target: " + tok
);
714 static int precedence(StringRef op
) {
715 return StringSwitch
<int>(op
)
716 .Cases("*", "/", "%", 11)
718 .Cases("<<", ">>", 9)
719 .Cases("<", "<=", ">", ">=", 8)
720 .Cases("==", "!=", 7)
730 StringMatcher
ScriptParser::readFilePatterns() {
731 StringMatcher Matcher
;
732 while (auto tok
= till(")"))
733 Matcher
.addPattern(SingleStringMatcher(tok
));
737 SortSectionPolicy
ScriptParser::peekSortKind() {
738 return StringSwitch
<SortSectionPolicy
>(peek())
739 .Case("REVERSE", SortSectionPolicy::Reverse
)
740 .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name
)
741 .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment
)
742 .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority
)
743 .Case("SORT_NONE", SortSectionPolicy::None
)
744 .Default(SortSectionPolicy::Default
);
747 SortSectionPolicy
ScriptParser::readSortKind() {
748 SortSectionPolicy ret
= peekSortKind();
749 if (ret
!= SortSectionPolicy::Default
)
754 // Reads SECTIONS command contents in the following form:
756 // <contents> ::= <elem>*
757 // <elem> ::= <exclude>? <glob-pattern>
758 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
762 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
764 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
765 // The semantics of that is section .foo in any file, section .bar in
766 // any file but a.o, and section .baz in any file but b.o.
767 SmallVector
<SectionPattern
, 0> ScriptParser::readInputSectionsList() {
768 SmallVector
<SectionPattern
, 0> ret
;
769 while (!errCount(ctx
) && peek() != ")") {
770 StringMatcher excludeFilePat
;
771 if (consume("EXCLUDE_FILE")) {
773 excludeFilePat
= readFilePatterns();
776 StringMatcher SectionMatcher
;
777 // Break if the next token is ), EXCLUDE_FILE, or SORT*.
778 while (!errCount(ctx
) && peekSortKind() == SortSectionPolicy::Default
) {
779 StringRef s
= peek();
780 if (s
== ")" || s
== "EXCLUDE_FILE")
782 // Detect common mistakes when certain non-wildcard meta characters are
783 // used without a closing ')'.
784 if (!s
.empty() && strchr("(){}", s
[0])) {
786 setError("section pattern is expected");
789 SectionMatcher
.addPattern(readName());
792 if (!SectionMatcher
.empty())
793 ret
.push_back({std::move(excludeFilePat
), std::move(SectionMatcher
)});
794 else if (excludeFilePat
.empty())
797 setError("section pattern is expected");
802 // Reads contents of "SECTIONS" directive. That directive contains a
803 // list of glob patterns for input sections. The grammar is as follows.
805 // <patterns> ::= <section-list>
806 // | <sort> "(" <section-list> ")"
807 // | <sort> "(" <sort> "(" <section-list> ")" ")"
809 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
810 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
812 // <section-list> is parsed by readInputSectionsList().
813 InputSectionDescription
*
814 ScriptParser::readInputSectionRules(StringRef filePattern
, uint64_t withFlags
,
815 uint64_t withoutFlags
) {
817 make
<InputSectionDescription
>(filePattern
, withFlags
, withoutFlags
);
820 while (peek() != ")" && !atEOF()) {
821 SortSectionPolicy outer
= readSortKind();
822 SortSectionPolicy inner
= SortSectionPolicy::Default
;
823 SmallVector
<SectionPattern
, 0> v
;
824 if (outer
!= SortSectionPolicy::Default
) {
826 inner
= readSortKind();
827 if (inner
!= SortSectionPolicy::Default
) {
829 v
= readInputSectionsList();
832 v
= readInputSectionsList();
836 v
= readInputSectionsList();
839 for (SectionPattern
&pat
: v
) {
840 pat
.sortInner
= inner
;
841 pat
.sortOuter
= outer
;
844 std::move(v
.begin(), v
.end(), std::back_inserter(cmd
->sectionPatterns
));
850 InputSectionDescription
*
851 ScriptParser::readInputSectionDescription(StringRef tok
) {
852 // Input section wildcard can be surrounded by KEEP.
853 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
854 uint64_t withFlags
= 0;
855 uint64_t withoutFlags
= 0;
858 if (consume("INPUT_SECTION_FLAGS"))
859 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
862 InputSectionDescription
*cmd
;
864 cmd
= make
<InputSectionDescription
>(StringRef
{}, withFlags
, withoutFlags
,
865 readSectionClassName());
867 cmd
= readInputSectionRules(tok
, withFlags
, withoutFlags
);
869 ctx
.script
->keptSections
.push_back(cmd
);
872 if (tok
== "INPUT_SECTION_FLAGS") {
873 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
877 return make
<InputSectionDescription
>(StringRef
{}, withFlags
, withoutFlags
,
878 readSectionClassName());
879 return readInputSectionRules(tok
, withFlags
, withoutFlags
);
882 void ScriptParser::readSort() {
884 expect("CONSTRUCTORS");
888 Expr
ScriptParser::readAssert() {
892 StringRef msg
= readName();
895 return [=, s
= ctx
.script
, &ctx
= ctx
]() -> ExprValue
{
904 constexpr std::pair
<const char *, unsigned> typeMap
[] = {
905 ECase(SHT_PROGBITS
), ECase(SHT_NOTE
), ECase(SHT_NOBITS
),
906 ECase(SHT_INIT_ARRAY
), ECase(SHT_FINI_ARRAY
), ECase(SHT_PREINIT_ARRAY
),
910 // Tries to read the special directive for an output section definition which
911 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
913 bool ScriptParser::readSectionDirective(OutputSection
*cmd
, StringRef tok
) {
914 if (tok
!= "NOLOAD" && tok
!= "COPY" && tok
!= "INFO" && tok
!= "OVERLAY" &&
918 if (consume("NOLOAD")) {
919 cmd
->type
= SHT_NOBITS
;
920 cmd
->typeIsSet
= true;
921 } else if (consume("TYPE")) {
923 StringRef value
= peek();
924 auto it
= llvm::find_if(typeMap
, [=](auto e
) { return e
.first
== value
; });
925 if (it
!= std::end(typeMap
)) {
926 // The value is a recognized literal SHT_*.
927 cmd
->type
= it
->second
;
929 } else if (value
.starts_with("SHT_")) {
930 setError("unknown section type " + value
);
932 // Otherwise, read an expression.
933 cmd
->type
= readExpr()().getValue();
935 cmd
->typeIsSet
= true;
937 skip(); // This is "COPY", "INFO" or "OVERLAY".
938 cmd
->nonAlloc
= true;
944 // Reads an expression and/or the special directive for an output
945 // section definition. Directive is one of following: "(NOLOAD)",
946 // "(COPY)", "(INFO)" or "(OVERLAY)".
948 // An output section name can be followed by an address expression
949 // and/or directive. This grammar is not LL(1) because "(" can be
950 // interpreted as either the beginning of some expression or beginning
953 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
954 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
955 void ScriptParser::readSectionAddressType(OutputSection
*cmd
) {
957 // Temporarily set inExpr to support TYPE=<value> without spaces.
958 SaveAndRestore
saved(inExpr
, true);
959 if (readSectionDirective(cmd
, peek()))
961 cmd
->addrExpr
= readExpr();
964 cmd
->addrExpr
= readExpr();
968 SaveAndRestore
saved(inExpr
, true);
969 StringRef tok
= peek();
970 if (!readSectionDirective(cmd
, tok
))
971 setError("unknown section directive: " + tok
);
975 static Expr
checkAlignment(Ctx
&ctx
, Expr e
, std::string
&loc
) {
977 uint64_t alignment
= std::max((uint64_t)1, e().getValue());
978 if (!isPowerOf2_64(alignment
)) {
979 ErrAlways(ctx
) << loc
<< ": alignment must be power of 2";
980 return (uint64_t)1; // Return a dummy value.
986 OutputDesc
*ScriptParser::readOverlaySectionDescription() {
988 ctx
.script
->createOutputSection(readName(), getCurrentLocation());
989 osd
->osec
.inOverlay
= true;
991 while (auto tok
= till("}")) {
992 uint64_t withFlags
= 0;
993 uint64_t withoutFlags
= 0;
994 if (tok
== "INPUT_SECTION_FLAGS") {
995 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
999 osd
->osec
.commands
.push_back(make
<InputSectionDescription
>(
1000 StringRef
{}, withFlags
, withoutFlags
, readSectionClassName()));
1002 osd
->osec
.commands
.push_back(
1003 readInputSectionRules(tok
, withFlags
, withoutFlags
));
1005 osd
->osec
.phdrs
= readOutputSectionPhdrs();
1009 OutputDesc
*ScriptParser::readOutputSectionDescription(StringRef outSec
) {
1011 ctx
.script
->createOutputSection(unquote(outSec
), getCurrentLocation());
1012 OutputSection
*osec
= &cmd
->osec
;
1013 // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.
1014 osec
->relro
= ctx
.script
->seenDataAlign
&& !ctx
.script
->seenRelroEnd
;
1016 size_t symbolsReferenced
= ctx
.script
->referencedSymbols
.size();
1019 readSectionAddressType(osec
);
1022 std::string location
= getCurrentLocation();
1024 osec
->lmaExpr
= readParenExpr();
1025 if (consume("ALIGN"))
1026 osec
->alignExpr
= checkAlignment(ctx
, readParenExpr(), location
);
1027 if (consume("SUBALIGN"))
1028 osec
->subalignExpr
= checkAlignment(ctx
, readParenExpr(), location
);
1030 // Parse constraints.
1031 if (consume("ONLY_IF_RO"))
1032 osec
->constraint
= ConstraintKind::ReadOnly
;
1033 if (consume("ONLY_IF_RW"))
1034 osec
->constraint
= ConstraintKind::ReadWrite
;
1037 while (auto tok
= till("}")) {
1039 // Empty commands are allowed. Do nothing here.
1040 } else if (SymbolAssignment
*assign
= readAssignment(tok
)) {
1041 osec
->commands
.push_back(assign
);
1042 } else if (ByteCommand
*data
= readByteCommand(tok
)) {
1043 osec
->commands
.push_back(data
);
1044 } else if (tok
== "CONSTRUCTORS") {
1045 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1046 // by name. This is for very old file formats such as ECOFF/XCOFF.
1047 // For ELF, we should ignore.
1048 } else if (tok
== "FILL") {
1049 // We handle the FILL command as an alias for =fillexp section attribute,
1050 // which is different from what GNU linkers do.
1051 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1053 setError("( expected, but got " + peek());
1054 osec
->filler
= readFill();
1055 } else if (tok
== "SORT") {
1057 } else if (tok
== "INCLUDE") {
1059 } else if (tok
== "(" || tok
== ")") {
1060 setError("expected filename pattern");
1061 } else if (peek() == "(") {
1062 osec
->commands
.push_back(readInputSectionDescription(tok
));
1064 // We have a file name and no input sections description. It is not a
1065 // commonly used syntax, but still acceptable. In that case, all sections
1066 // from the file will be included.
1067 // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
1068 // handle this case here as it will already have been matched by the
1070 auto *isd
= make
<InputSectionDescription
>(tok
);
1071 isd
->sectionPatterns
.push_back({{}, StringMatcher("*")});
1072 osec
->commands
.push_back(isd
);
1077 osec
->memoryRegionName
= std::string(readName());
1079 if (consume("AT")) {
1081 osec
->lmaRegionName
= std::string(readName());
1084 if (osec
->lmaExpr
&& !osec
->lmaRegionName
.empty())
1085 ErrAlways(ctx
) << "section can't have both LMA and a load region";
1087 osec
->phdrs
= readOutputSectionPhdrs();
1089 if (peek() == "=" || peek().starts_with("=")) {
1092 osec
->filler
= readFill();
1096 // Consume optional comma following output section command.
1099 if (ctx
.script
->referencedSymbols
.size() > symbolsReferenced
)
1100 osec
->expressionsUseSymbols
= true;
1104 // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
1105 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1106 // We do not support using symbols in such expressions.
1108 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
1109 // size, while ld.gold always handles it as a 32-bit big-endian number.
1110 // We are compatible with ld.gold because it's easier to implement.
1111 // Also, we require that expressions with operators must be wrapped into
1112 // round brackets. We did it to resolve the ambiguity when parsing scripts like:
1113 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
1114 std::array
<uint8_t, 4> ScriptParser::readFill() {
1115 uint64_t value
= readPrimary()().val
;
1116 if (value
> UINT32_MAX
)
1117 setError("filler expression result does not fit 32-bit: 0x" +
1118 Twine::utohexstr(value
));
1120 std::array
<uint8_t, 4> buf
;
1121 write32be(buf
.data(), (uint32_t)value
);
1125 SymbolAssignment
*ScriptParser::readProvideHidden(bool provide
, bool hidden
) {
1127 StringRef name
= readName(), eq
= peek();
1129 setError("= expected, but got " + next());
1134 llvm::SaveAndRestore
saveActiveProvideSym(activeProvideSym
);
1136 activeProvideSym
= name
;
1137 SymbolAssignment
*cmd
= readSymbolAssignment(name
);
1138 cmd
->provide
= provide
;
1139 cmd
->hidden
= hidden
;
1144 // Replace whitespace sequence (including \n) with one single space. The output
1146 static void squeezeSpaces(std::string
&str
) {
1148 auto it
= str
.begin();
1150 if (!isSpace(c
) || (c
= ' ') != prev
)
1152 str
.erase(it
, str
.end());
1155 SymbolAssignment
*ScriptParser::readAssignment(StringRef tok
) {
1156 // Assert expression returns Dot, so this is equal to ".=."
1157 if (tok
== "ASSERT")
1158 return make
<SymbolAssignment
>(".", readAssert(), 0, getCurrentLocation());
1160 const char *oldS
= prevTok
.data();
1161 SymbolAssignment
*cmd
= nullptr;
1162 bool savedSeenRelroEnd
= ctx
.script
->seenRelroEnd
;
1163 const StringRef op
= peek();
1165 SaveAndRestore
saved(inExpr
, true);
1166 if (op
.starts_with("=")) {
1167 // Support = followed by an expression without whitespace.
1168 cmd
= readSymbolAssignment(unquote(tok
));
1169 } else if ((op
.size() == 2 && op
[1] == '=' && strchr("+-*/&^|", op
[0])) ||
1170 op
== "<<=" || op
== ">>=") {
1171 cmd
= readSymbolAssignment(unquote(tok
));
1172 } else if (tok
== "PROVIDE") {
1173 cmd
= readProvideHidden(true, false);
1174 } else if (tok
== "HIDDEN") {
1175 cmd
= readProvideHidden(false, true);
1176 } else if (tok
== "PROVIDE_HIDDEN") {
1177 cmd
= readProvideHidden(true, true);
1182 cmd
->dataSegmentRelroEnd
= !savedSeenRelroEnd
&& ctx
.script
->seenRelroEnd
;
1183 cmd
->commandString
= StringRef(oldS
, curTok
.data() - oldS
).str();
1184 squeezeSpaces(cmd
->commandString
);
1190 StringRef
ScriptParser::readName() { return unquote(next()); }
1192 SymbolAssignment
*ScriptParser::readSymbolAssignment(StringRef name
) {
1193 StringRef op
= next();
1194 assert(op
== "=" || op
== "*=" || op
== "/=" || op
== "+=" || op
== "-=" ||
1195 op
== "&=" || op
== "^=" || op
== "|=" || op
== "<<=" || op
== ">>=");
1196 // Note: GNU ld does not support %=.
1197 Expr e
= readExpr();
1199 std::string loc
= getCurrentLocation();
1200 e
= [=, s
= ctx
.script
, c
= op
[0], &ctx
= ctx
]() -> ExprValue
{
1201 ExprValue lhs
= s
->getSymbolValue(name
, loc
);
1204 return lhs
.getValue() * e().getValue();
1206 if (uint64_t rv
= e().getValue())
1207 return lhs
.getValue() / rv
;
1208 ErrAlways(ctx
) << loc
<< ": division by zero";
1211 return add(*s
, lhs
, e());
1213 return sub(lhs
, e());
1215 return lhs
.getValue() << e().getValue() % 64;
1217 return lhs
.getValue() >> e().getValue() % 64;
1219 return lhs
.getValue() & e().getValue();
1221 return lhs
.getValue() ^ e().getValue();
1223 return lhs
.getValue() | e().getValue();
1225 llvm_unreachable("");
1229 return make
<SymbolAssignment
>(name
, e
, ctx
.scriptSymOrderCounter
++,
1230 getCurrentLocation());
1233 // This is an operator-precedence parser to parse a linker
1234 // script expression.
1235 Expr
ScriptParser::readExpr() {
1236 // Our lexer is context-aware. Set the in-expression bit so that
1237 // they apply different tokenization rules.
1238 SaveAndRestore
saved(inExpr
, true);
1239 Expr e
= readExpr1(readPrimary(), 0);
1243 Expr
ScriptParser::combine(StringRef op
, Expr l
, Expr r
) {
1245 return [=, s
= ctx
.script
] { return add(*s
, l(), r()); };
1247 return [=] { return sub(l(), r()); };
1249 return [=] { return l().getValue() * r().getValue(); };
1251 std::string loc
= getCurrentLocation();
1252 return [=, &ctx
= ctx
]() -> uint64_t {
1253 if (uint64_t rv
= r().getValue())
1254 return l().getValue() / rv
;
1255 ErrAlways(ctx
) << loc
<< ": division by zero";
1260 std::string loc
= getCurrentLocation();
1261 return [=, &ctx
= ctx
]() -> uint64_t {
1262 if (uint64_t rv
= r().getValue())
1263 return l().getValue() % rv
;
1264 ErrAlways(ctx
) << loc
<< ": modulo by zero";
1269 return [=] { return l().getValue() << r().getValue() % 64; };
1271 return [=] { return l().getValue() >> r().getValue() % 64; };
1273 return [=] { return l().getValue() < r().getValue(); };
1275 return [=] { return l().getValue() > r().getValue(); };
1277 return [=] { return l().getValue() >= r().getValue(); };
1279 return [=] { return l().getValue() <= r().getValue(); };
1281 return [=] { return l().getValue() == r().getValue(); };
1283 return [=] { return l().getValue() != r().getValue(); };
1285 return [=] { return l().getValue() || r().getValue(); };
1287 return [=] { return l().getValue() && r().getValue(); };
1289 return [=, s
= ctx
.script
] { return bitAnd(*s
, l(), r()); };
1291 return [=, s
= ctx
.script
] { return bitXor(*s
, l(), r()); };
1293 return [=, s
= ctx
.script
] { return bitOr(*s
, l(), r()); };
1294 llvm_unreachable("invalid operator");
1297 // This is a part of the operator-precedence parser. This function
1298 // assumes that the remaining token stream starts with an operator.
1299 Expr
ScriptParser::readExpr1(Expr lhs
, int minPrec
) {
1300 while (!atEOF() && !errCount(ctx
)) {
1301 // Read an operator and an expression.
1302 StringRef op1
= peek();
1303 if (precedence(op1
) < minPrec
)
1307 return readTernary(lhs
);
1308 Expr rhs
= readPrimary();
1310 // Evaluate the remaining part of the expression first if the
1311 // next operator has greater precedence than the previous one.
1312 // For example, if we have read "+" and "3", and if the next
1313 // operator is "*", then we'll evaluate 3 * ... part first.
1315 StringRef op2
= peek();
1316 if (precedence(op2
) <= precedence(op1
))
1318 rhs
= readExpr1(rhs
, precedence(op2
));
1321 lhs
= combine(op1
, lhs
, rhs
);
1326 Expr
ScriptParser::getPageSize() {
1327 std::string location
= getCurrentLocation();
1328 return [=, &ctx
= this->ctx
]() -> uint64_t {
1330 return ctx
.arg
.commonPageSize
;
1331 ErrAlways(ctx
) << location
<< ": unable to calculate page size";
1332 return 4096; // Return a dummy value.
1336 Expr
ScriptParser::readConstant() {
1337 StringRef s
= readParenName();
1338 if (s
== "COMMONPAGESIZE")
1339 return getPageSize();
1340 if (s
== "MAXPAGESIZE")
1341 return [&ctx
= this->ctx
] { return ctx
.arg
.maxPageSize
; };
1342 setError("unknown constant: " + s
);
1343 return [] { return 0; };
1346 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1347 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1348 // have "K" (Ki) or "M" (Mi) suffixes.
1349 static std::optional
<uint64_t> parseInt(StringRef tok
) {
1352 if (tok
.starts_with_insensitive("0x")) {
1353 if (!to_integer(tok
.substr(2), val
, 16))
1354 return std::nullopt
;
1357 if (tok
.ends_with_insensitive("H")) {
1358 if (!to_integer(tok
.drop_back(), val
, 16))
1359 return std::nullopt
;
1364 if (tok
.ends_with_insensitive("K")) {
1365 if (!to_integer(tok
.drop_back(), val
, 10))
1366 return std::nullopt
;
1369 if (tok
.ends_with_insensitive("M")) {
1370 if (!to_integer(tok
.drop_back(), val
, 10))
1371 return std::nullopt
;
1372 return val
* 1024 * 1024;
1374 if (!to_integer(tok
, val
, 10))
1375 return std::nullopt
;
1379 ByteCommand
*ScriptParser::readByteCommand(StringRef tok
) {
1380 int size
= StringSwitch
<int>(tok
)
1389 const char *oldS
= prevTok
.data();
1390 Expr e
= readParenExpr();
1391 std::string commandString
= StringRef(oldS
, curBuf
.s
.data() - oldS
).str();
1392 squeezeSpaces(commandString
);
1393 return make
<ByteCommand
>(e
, size
, std::move(commandString
));
1396 static std::optional
<uint64_t> parseFlag(StringRef tok
) {
1397 if (std::optional
<uint64_t> asInt
= parseInt(tok
))
1399 #define CASE_ENT(enum) #enum, ELF::enum
1400 return StringSwitch
<std::optional
<uint64_t>>(tok
)
1401 .Case(CASE_ENT(SHF_WRITE
))
1402 .Case(CASE_ENT(SHF_ALLOC
))
1403 .Case(CASE_ENT(SHF_EXECINSTR
))
1404 .Case(CASE_ENT(SHF_MERGE
))
1405 .Case(CASE_ENT(SHF_STRINGS
))
1406 .Case(CASE_ENT(SHF_INFO_LINK
))
1407 .Case(CASE_ENT(SHF_LINK_ORDER
))
1408 .Case(CASE_ENT(SHF_OS_NONCONFORMING
))
1409 .Case(CASE_ENT(SHF_GROUP
))
1410 .Case(CASE_ENT(SHF_TLS
))
1411 .Case(CASE_ENT(SHF_COMPRESSED
))
1412 .Case(CASE_ENT(SHF_EXCLUDE
))
1413 .Case(CASE_ENT(SHF_ARM_PURECODE
))
1414 .Default(std::nullopt
);
1418 // Reads the '(' <flags> ')' list of section flags in
1419 // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1421 // <flags> ::= <flag>
1423 // <flag> ::= Recognized Flag Name, or Integer value of flag.
1424 // If the first character of <flag> is a ! then this means without flag,
1425 // otherwise with flag.
1426 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1427 // without flag SHF_WRITE.
1428 std::pair
<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1429 uint64_t withFlags
= 0;
1430 uint64_t withoutFlags
= 0;
1432 while (!errCount(ctx
)) {
1433 StringRef tok
= readName();
1434 bool without
= tok
.consume_front("!");
1435 if (std::optional
<uint64_t> flag
= parseFlag(tok
)) {
1437 withoutFlags
|= *flag
;
1441 setError("unrecognised flag: " + tok
);
1445 if (!consume("&")) {
1447 setError("expected & or )");
1450 return std::make_pair(withFlags
, withoutFlags
);
1453 StringRef
ScriptParser::readParenName() {
1457 StringRef tok
= readName();
1463 static void checkIfExists(LinkerScript
&script
, const OutputSection
&osec
,
1464 StringRef location
) {
1465 if (osec
.location
.empty() && script
.errorOnMissingSection
)
1466 script
.recordError(location
+ ": undefined section " + osec
.name
);
1469 static bool isValidSymbolName(StringRef s
) {
1470 auto valid
= [](char c
) {
1471 return isAlnum(c
) || c
== '$' || c
== '.' || c
== '_';
1473 return !s
.empty() && !isDigit(s
[0]) && llvm::all_of(s
, valid
);
1476 Expr
ScriptParser::readPrimary() {
1478 return readParenExpr();
1481 Expr e
= readPrimary();
1482 return [=] { return ~e().getValue(); };
1485 Expr e
= readPrimary();
1486 return [=] { return !e().getValue(); };
1489 Expr e
= readPrimary();
1490 return [=] { return -e().getValue(); };
1493 StringRef tok
= next();
1494 std::string location
= getCurrentLocation();
1496 // Built-in functions are parsed here.
1497 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1498 if (tok
== "ABSOLUTE") {
1499 Expr inner
= readParenExpr();
1501 ExprValue i
= inner();
1502 i
.forceAbsolute
= true;
1506 if (tok
== "ADDR") {
1507 StringRef name
= readParenName();
1508 OutputSection
*osec
= &ctx
.script
->getOrCreateOutputSection(name
)->osec
;
1509 osec
->usedInExpression
= true;
1510 return [=, s
= ctx
.script
]() -> ExprValue
{
1511 checkIfExists(*s
, *osec
, location
);
1512 return {osec
, false, 0, location
};
1515 if (tok
== "ALIGN") {
1517 Expr e
= readExpr();
1519 e
= checkAlignment(ctx
, e
, location
);
1520 return [=, s
= ctx
.script
] {
1521 return alignToPowerOf2(s
->getDot(), e().getValue());
1525 Expr e2
= checkAlignment(ctx
, readExpr(), location
);
1529 v
.alignment
= e2().getValue();
1533 if (tok
== "ALIGNOF") {
1534 StringRef name
= readParenName();
1535 OutputSection
*osec
= &ctx
.script
->getOrCreateOutputSection(name
)->osec
;
1536 return [=, s
= ctx
.script
] {
1537 checkIfExists(*s
, *osec
, location
);
1538 return osec
->addralign
;
1541 if (tok
== "ASSERT")
1542 return readAssert();
1543 if (tok
== "CONSTANT")
1544 return readConstant();
1545 if (tok
== "DATA_SEGMENT_ALIGN") {
1547 Expr e
= readExpr();
1551 ctx
.script
->seenDataAlign
= true;
1552 return [=, s
= ctx
.script
] {
1553 uint64_t align
= std::max(uint64_t(1), e().getValue());
1554 return (s
->getDot() + align
- 1) & -align
;
1557 if (tok
== "DATA_SEGMENT_END") {
1561 return [s
= ctx
.script
] { return s
->getDot(); };
1563 if (tok
== "DATA_SEGMENT_RELRO_END") {
1564 // GNU linkers implements more complicated logic to handle
1565 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1566 // just align to the next page boundary for simplicity.
1572 ctx
.script
->seenRelroEnd
= true;
1573 return [&ctx
= this->ctx
] {
1574 return alignToPowerOf2(ctx
.script
->getDot(), ctx
.arg
.maxPageSize
);
1577 if (tok
== "DEFINED") {
1578 StringRef name
= readParenName();
1579 // Return 1 if s is defined. If the definition is only found in a linker
1580 // script, it must happen before this DEFINED.
1581 auto order
= ctx
.scriptSymOrderCounter
++;
1582 return [=, &ctx
= this->ctx
] {
1583 Symbol
*s
= ctx
.symtab
->find(name
);
1584 return s
&& s
->isDefined() && ctx
.scriptSymOrder
.lookup(s
) < order
? 1
1588 if (tok
== "LENGTH") {
1589 StringRef name
= readParenName();
1590 if (ctx
.script
->memoryRegions
.count(name
) == 0) {
1591 setError("memory region not defined: " + name
);
1592 return [] { return 0; };
1594 return ctx
.script
->memoryRegions
[name
]->length
;
1596 if (tok
== "LOADADDR") {
1597 StringRef name
= readParenName();
1598 OutputSection
*osec
= &ctx
.script
->getOrCreateOutputSection(name
)->osec
;
1599 osec
->usedInExpression
= true;
1600 return [=, s
= ctx
.script
] {
1601 checkIfExists(*s
, *osec
, location
);
1602 return osec
->getLMA();
1605 if (tok
== "LOG2CEIL") {
1607 Expr a
= readExpr();
1610 // LOG2CEIL(0) is defined to be 0.
1611 return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1614 if (tok
== "MAX" || tok
== "MIN") {
1616 Expr a
= readExpr();
1618 Expr b
= readExpr();
1621 return [=] { return std::min(a().getValue(), b().getValue()); };
1622 return [=] { return std::max(a().getValue(), b().getValue()); };
1624 if (tok
== "ORIGIN") {
1625 StringRef name
= readParenName();
1626 if (ctx
.script
->memoryRegions
.count(name
) == 0) {
1627 setError("memory region not defined: " + name
);
1628 return [] { return 0; };
1630 return ctx
.script
->memoryRegions
[name
]->origin
;
1632 if (tok
== "SEGMENT_START") {
1636 Expr e
= readExpr();
1638 return [=] { return e(); };
1640 if (tok
== "SIZEOF") {
1641 StringRef name
= readParenName();
1642 OutputSection
*cmd
= &ctx
.script
->getOrCreateOutputSection(name
)->osec
;
1643 // Linker script does not create an output section if its content is empty.
1644 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1646 return [=] { return cmd
->size
; };
1648 if (tok
== "SIZEOF_HEADERS")
1649 return [=, &ctx
= ctx
] { return elf::getHeaderSize(ctx
); };
1653 return [=, s
= ctx
.script
] { return s
->getSymbolValue(tok
, location
); };
1655 // Tok is a literal number.
1656 if (std::optional
<uint64_t> val
= parseInt(tok
))
1657 return [=] { return *val
; };
1659 // Tok is a symbol name.
1660 if (tok
.starts_with("\""))
1662 else if (!isValidSymbolName(tok
))
1663 setError("malformed number: " + tok
);
1664 if (activeProvideSym
)
1665 ctx
.script
->provideMap
[*activeProvideSym
].push_back(tok
);
1667 ctx
.script
->referencedSymbols
.push_back(tok
);
1668 return [=, s
= ctx
.script
] { return s
->getSymbolValue(tok
, location
); };
1671 Expr
ScriptParser::readTernary(Expr cond
) {
1672 Expr l
= readExpr();
1674 Expr r
= readExpr();
1675 return [=] { return cond().getValue() ? l() : r(); };
1678 Expr
ScriptParser::readParenExpr() {
1680 Expr e
= readExpr();
1685 SmallVector
<StringRef
, 0> ScriptParser::readOutputSectionPhdrs() {
1686 SmallVector
<StringRef
, 0> phdrs
;
1687 while (!errCount(ctx
) && peek().starts_with(":")) {
1688 StringRef tok
= next();
1689 phdrs
.push_back((tok
.size() == 1) ? readName() : tok
.substr(1));
1694 // Read a program header type name. The next token must be a
1695 // name of a program header type or a constant (e.g. "0x3").
1696 unsigned ScriptParser::readPhdrType() {
1697 StringRef tok
= next();
1698 if (std::optional
<uint64_t> val
= parseInt(tok
))
1701 unsigned ret
= StringSwitch
<unsigned>(tok
)
1702 .Case("PT_NULL", PT_NULL
)
1703 .Case("PT_LOAD", PT_LOAD
)
1704 .Case("PT_DYNAMIC", PT_DYNAMIC
)
1705 .Case("PT_INTERP", PT_INTERP
)
1706 .Case("PT_NOTE", PT_NOTE
)
1707 .Case("PT_SHLIB", PT_SHLIB
)
1708 .Case("PT_PHDR", PT_PHDR
)
1709 .Case("PT_TLS", PT_TLS
)
1710 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME
)
1711 .Case("PT_GNU_STACK", PT_GNU_STACK
)
1712 .Case("PT_GNU_RELRO", PT_GNU_RELRO
)
1713 .Case("PT_OPENBSD_MUTABLE", PT_OPENBSD_MUTABLE
)
1714 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE
)
1715 .Case("PT_OPENBSD_SYSCALLS", PT_OPENBSD_SYSCALLS
)
1716 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED
)
1717 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA
)
1720 if (ret
== (unsigned)-1) {
1721 setError("invalid program header type: " + tok
);
1727 // Reads an anonymous version declaration.
1728 void ScriptParser::readAnonymousDeclaration() {
1729 SmallVector
<SymbolVersion
, 0> locals
;
1730 SmallVector
<SymbolVersion
, 0> globals
;
1731 std::tie(locals
, globals
) = readSymbols();
1732 for (const SymbolVersion
&pat
: locals
)
1733 ctx
.arg
.versionDefinitions
[VER_NDX_LOCAL
].localPatterns
.push_back(pat
);
1734 for (const SymbolVersion
&pat
: globals
)
1735 ctx
.arg
.versionDefinitions
[VER_NDX_GLOBAL
].nonLocalPatterns
.push_back(pat
);
1740 // Reads a non-anonymous version definition,
1741 // e.g. "VerStr { global: foo; bar; local: *; };".
1742 void ScriptParser::readVersionDeclaration(StringRef verStr
) {
1743 // Read a symbol list.
1744 SmallVector
<SymbolVersion
, 0> locals
;
1745 SmallVector
<SymbolVersion
, 0> globals
;
1746 std::tie(locals
, globals
) = readSymbols();
1748 // Create a new version definition and add that to the global symbols.
1749 VersionDefinition ver
;
1751 ver
.nonLocalPatterns
= std::move(globals
);
1752 ver
.localPatterns
= std::move(locals
);
1753 ver
.id
= ctx
.arg
.versionDefinitions
.size();
1754 ctx
.arg
.versionDefinitions
.push_back(ver
);
1756 // Each version may have a parent version. For example, "Ver2"
1757 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1758 // as a parent. This version hierarchy is, probably against your
1759 // instinct, purely for hint; the runtime doesn't care about it
1760 // at all. In LLD, we simply ignore it.
1765 bool elf::hasWildcard(StringRef s
) {
1766 return s
.find_first_of("?*[") != StringRef::npos
;
1769 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1770 std::pair
<SmallVector
<SymbolVersion
, 0>, SmallVector
<SymbolVersion
, 0>>
1771 ScriptParser::readSymbols() {
1772 SmallVector
<SymbolVersion
, 0> locals
;
1773 SmallVector
<SymbolVersion
, 0> globals
;
1774 SmallVector
<SymbolVersion
, 0> *v
= &globals
;
1776 while (auto tok
= till("}")) {
1777 if (tok
== "extern") {
1778 SmallVector
<SymbolVersion
, 0> ext
= readVersionExtern();
1779 v
->insert(v
->end(), ext
.begin(), ext
.end());
1781 if (tok
== "local:" || (tok
== "local" && consume(":"))) {
1785 if (tok
== "global:" || (tok
== "global" && consume(":"))) {
1789 v
->push_back({unquote(tok
), false, hasWildcard(tok
)});
1793 return {locals
, globals
};
1796 // Reads an "extern C++" directive, e.g.,
1797 // "extern "C++" { ns::*; "f(int, double)"; };"
1799 // The last semicolon is optional. E.g. this is OK:
1800 // "extern "C++" { ns::*; "f(int, double)" };"
1801 SmallVector
<SymbolVersion
, 0> ScriptParser::readVersionExtern() {
1802 StringRef tok
= next();
1803 bool isCXX
= tok
== "\"C++\"";
1804 if (!isCXX
&& tok
!= "\"C\"")
1805 setError("Unknown language");
1808 SmallVector
<SymbolVersion
, 0> ret
;
1809 while (auto tok
= till("}")) {
1811 {unquote(tok
), isCXX
, !tok
.str
.starts_with("\"") && hasWildcard(tok
)});
1819 Expr
ScriptParser::readMemoryAssignment(StringRef s1
, StringRef s2
,
1821 if (!consume(s1
) && !consume(s2
) && !consume(s3
)) {
1822 setError("expected one of: " + s1
+ ", " + s2
+ ", or " + s3
);
1823 return [] { return 0; };
1829 // Parse the MEMORY command as specified in:
1830 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1832 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1833 void ScriptParser::readMemory() {
1835 while (auto tok
= till("}")) {
1836 if (tok
== "INCLUDE") {
1842 uint32_t invFlags
= 0;
1843 uint32_t negFlags
= 0;
1844 uint32_t negInvFlags
= 0;
1846 readMemoryAttributes(flags
, invFlags
, negFlags
, negInvFlags
);
1851 Expr origin
= readMemoryAssignment("ORIGIN", "org", "o");
1853 Expr length
= readMemoryAssignment("LENGTH", "len", "l");
1855 // Add the memory region to the region map.
1856 MemoryRegion
*mr
= make
<MemoryRegion
>(tok
, origin
, length
, flags
, invFlags
,
1857 negFlags
, negInvFlags
);
1858 if (!ctx
.script
->memoryRegions
.insert({tok
, mr
}).second
)
1859 setError("region '" + tok
+ "' already defined");
1863 // This function parses the attributes used to match against section
1864 // flags when placing output sections in a memory region. These flags
1865 // are only used when an explicit memory region name is not used.
1866 void ScriptParser::readMemoryAttributes(uint32_t &flags
, uint32_t &invFlags
,
1868 uint32_t &negInvFlags
) {
1869 bool invert
= false;
1871 for (char c
: next().lower()) {
1874 std::swap(flags
, negFlags
);
1875 std::swap(invFlags
, negInvFlags
);
1881 flags
|= SHF_EXECINSTR
;
1885 invFlags
|= SHF_WRITE
;
1887 setError("invalid memory region attribute");
1891 std::swap(flags
, negFlags
);
1892 std::swap(invFlags
, negInvFlags
);
1896 void elf::readLinkerScript(Ctx
&ctx
, MemoryBufferRef mb
) {
1897 llvm::TimeTraceScope
timeScope("Read linker script",
1898 mb
.getBufferIdentifier());
1899 ScriptParser(ctx
, mb
).readLinkerScript();
1902 void elf::readVersionScript(Ctx
&ctx
, MemoryBufferRef mb
) {
1903 llvm::TimeTraceScope
timeScope("Read version script",
1904 mb
.getBufferIdentifier());
1905 ScriptParser(ctx
, mb
).readVersionScript();
1908 void elf::readDynamicList(Ctx
&ctx
, MemoryBufferRef mb
) {
1909 llvm::TimeTraceScope
timeScope("Read dynamic list", mb
.getBufferIdentifier());
1910 ScriptParser(ctx
, mb
).readDynamicList();
1913 void elf::readDefsym(Ctx
&ctx
, MemoryBufferRef mb
) {
1914 ScriptParser(ctx
, mb
).readDefsym();