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/StringSet.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/BinaryFormat/ELF.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SaveAndRestore.h"
36 #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(MemoryBufferRef mb
) : ScriptLexer(mb
) {
51 // Initialize IsUnderSysroot
52 if (config
->sysroot
== "")
54 StringRef path
= mb
.getBufferIdentifier();
55 for (; !path
.empty(); path
= sys::path::parent_path(path
)) {
56 if (!sys::fs::equivalent(config
->sysroot
, path
))
58 isUnderSysroot
= true;
63 void readLinkerScript();
64 void readVersionScript();
65 void readDynamicList();
66 void readDefsym(StringRef name
);
69 void addFile(StringRef path
);
79 void readOutputArch();
80 void readOutputFormat();
81 void readOverwriteSections();
83 void readRegionAlias();
88 void readVersionScriptCommand();
90 SymbolAssignment
*readSymbolAssignment(StringRef name
);
91 ByteCommand
*readByteCommand(StringRef tok
);
92 std::array
<uint8_t, 4> readFill();
93 bool readSectionDirective(OutputSection
*cmd
, StringRef tok1
, StringRef tok2
);
94 void readSectionAddressType(OutputSection
*cmd
);
95 OutputDesc
*readOverlaySectionDescription();
96 OutputDesc
*readOutputSectionDescription(StringRef outSec
);
97 SmallVector
<SectionCommand
*, 0> readOverlay();
98 SmallVector
<StringRef
, 0> readOutputSectionPhdrs();
99 std::pair
<uint64_t, uint64_t> readInputSectionFlags();
100 InputSectionDescription
*readInputSectionDescription(StringRef tok
);
101 StringMatcher
readFilePatterns();
102 SmallVector
<SectionPattern
, 0> readInputSectionsList();
103 InputSectionDescription
*readInputSectionRules(StringRef filePattern
,
105 uint64_t withoutFlags
);
106 unsigned readPhdrType();
107 SortSectionPolicy
peekSortKind();
108 SortSectionPolicy
readSortKind();
109 SymbolAssignment
*readProvideHidden(bool provide
, bool hidden
);
110 SymbolAssignment
*readAssignment(StringRef tok
);
116 Expr
readMemoryAssignment(StringRef
, StringRef
, StringRef
);
117 void readMemoryAttributes(uint32_t &flags
, uint32_t &invFlags
,
118 uint32_t &negFlags
, uint32_t &negInvFlags
);
120 Expr
combine(StringRef op
, Expr l
, Expr r
);
122 Expr
readExpr1(Expr lhs
, int minPrec
);
123 StringRef
readParenLiteral();
125 Expr
readTernary(Expr cond
);
126 Expr
readParenExpr();
128 // For parsing version script.
129 SmallVector
<SymbolVersion
, 0> readVersionExtern();
130 void readAnonymousDeclaration();
131 void readVersionDeclaration(StringRef verStr
);
133 std::pair
<SmallVector
<SymbolVersion
, 0>, SmallVector
<SymbolVersion
, 0>>
136 // True if a script being read is in the --sysroot directory.
137 bool isUnderSysroot
= false;
139 // A set to detect an INCLUDE() cycle.
144 static StringRef
unquote(StringRef s
) {
145 if (s
.starts_with("\""))
146 return s
.substr(1, s
.size() - 2);
150 // Some operations only support one non absolute value. Move the
151 // absolute one to the right hand side for convenience.
152 static void moveAbsRight(ExprValue
&a
, ExprValue
&b
) {
153 if (a
.sec
== nullptr || (a
.forceAbsolute
&& !b
.isAbsolute()))
156 error(a
.loc
+ ": at least one side of the expression must be absolute");
159 static ExprValue
add(ExprValue a
, ExprValue b
) {
161 return {a
.sec
, a
.forceAbsolute
, a
.getSectionOffset() + b
.getValue(), a
.loc
};
164 static ExprValue
sub(ExprValue a
, ExprValue b
) {
165 // The distance between two symbols in sections is absolute.
166 if (!a
.isAbsolute() && !b
.isAbsolute())
167 return a
.getValue() - b
.getValue();
168 return {a
.sec
, false, a
.getSectionOffset() - b
.getValue(), a
.loc
};
171 static ExprValue
bitAnd(ExprValue a
, ExprValue b
) {
173 return {a
.sec
, a
.forceAbsolute
,
174 (a
.getValue() & b
.getValue()) - a
.getSecAddr(), a
.loc
};
177 static ExprValue
bitXor(ExprValue a
, ExprValue b
) {
179 return {a
.sec
, a
.forceAbsolute
,
180 (a
.getValue() ^ b
.getValue()) - a
.getSecAddr(), a
.loc
};
183 static ExprValue
bitOr(ExprValue a
, ExprValue b
) {
185 return {a
.sec
, a
.forceAbsolute
,
186 (a
.getValue() | b
.getValue()) - a
.getSecAddr(), a
.loc
};
189 void ScriptParser::readDynamicList() {
191 SmallVector
<SymbolVersion
, 0> locals
;
192 SmallVector
<SymbolVersion
, 0> globals
;
193 std::tie(locals
, globals
) = readSymbols();
197 setError("EOF expected, but got " + next());
200 if (!locals
.empty()) {
201 setError("\"local:\" scope not supported in --dynamic-list");
205 for (SymbolVersion v
: globals
)
206 config
->dynamicList
.push_back(v
);
209 void ScriptParser::readVersionScript() {
210 readVersionScriptCommand();
212 setError("EOF expected, but got " + next());
215 void ScriptParser::readVersionScriptCommand() {
217 readAnonymousDeclaration();
221 while (!atEOF() && !errorCount() && peek() != "}") {
222 StringRef verStr
= next();
224 setError("anonymous version definition is used in "
225 "combination with other version definitions");
229 readVersionDeclaration(verStr
);
233 void ScriptParser::readVersion() {
235 readVersionScriptCommand();
239 void ScriptParser::readLinkerScript() {
241 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 (SymbolAssignment
*cmd
= readAssignment(tok
)) {
278 script
->sectionCommands
.push_back(cmd
);
280 setError("unknown directive: " + tok
);
285 void ScriptParser::readDefsym(StringRef name
) {
290 setError("EOF expected, but got " + next());
291 auto *cmd
= make
<SymbolAssignment
>(name
, e
, 0, getCurrentLocation());
292 script
->sectionCommands
.push_back(cmd
);
295 void ScriptParser::addFile(StringRef s
) {
296 if (isUnderSysroot
&& s
.starts_with("/")) {
297 SmallString
<128> pathData
;
298 StringRef path
= (config
->sysroot
+ s
).toStringRef(pathData
);
299 if (sys::fs::exists(path
))
300 ctx
.driver
.addFile(saver().save(path
), /*withLOption=*/false);
302 setError("cannot find " + s
+ " inside " + config
->sysroot
);
306 if (s
.starts_with("/")) {
307 // Case 1: s is an absolute path. Just open it.
308 ctx
.driver
.addFile(s
, /*withLOption=*/false);
309 } else if (s
.starts_with("=")) {
310 // Case 2: relative to the sysroot.
311 if (config
->sysroot
.empty())
312 ctx
.driver
.addFile(s
.substr(1), /*withLOption=*/false);
314 ctx
.driver
.addFile(saver().save(config
->sysroot
+ "/" + s
.substr(1)),
315 /*withLOption=*/false);
316 } else if (s
.starts_with("-l")) {
317 // Case 3: search in the list of library paths.
318 ctx
.driver
.addLibrary(s
.substr(2));
320 // Case 4: s is a relative path. Search in the directory of the script file.
321 std::string filename
= std::string(getCurrentMB().getBufferIdentifier());
322 StringRef directory
= sys::path::parent_path(filename
);
323 if (!directory
.empty()) {
324 SmallString
<0> path(directory
);
325 sys::path::append(path
, s
);
326 if (sys::fs::exists(path
)) {
327 ctx
.driver
.addFile(path
, /*withLOption=*/false);
331 // Then search in the current working directory.
332 if (sys::fs::exists(s
)) {
333 ctx
.driver
.addFile(s
, /*withLOption=*/false);
335 // Finally, search in the list of library paths.
336 if (std::optional
<std::string
> path
= findFromSearchPaths(s
))
337 ctx
.driver
.addFile(saver().save(*path
), /*withLOption=*/true);
339 setError("unable to find " + s
);
344 void ScriptParser::readAsNeeded() {
346 bool orig
= config
->asNeeded
;
347 config
->asNeeded
= true;
348 while (!errorCount() && !consume(")"))
349 addFile(unquote(next()));
350 config
->asNeeded
= orig
;
353 void ScriptParser::readEntry() {
354 // -e <symbol> takes predecence over ENTRY(<symbol>).
356 StringRef tok
= next();
357 if (config
->entry
.empty())
358 config
->entry
= unquote(tok
);
362 void ScriptParser::readExtern() {
364 while (!errorCount() && !consume(")"))
365 config
->undefined
.push_back(unquote(next()));
368 void ScriptParser::readGroup() {
369 bool orig
= InputFile::isInGroup
;
370 InputFile::isInGroup
= true;
372 InputFile::isInGroup
= orig
;
374 ++InputFile::nextGroupId
;
377 void ScriptParser::readInclude() {
378 StringRef tok
= unquote(next());
380 if (!seen
.insert(tok
).second
) {
381 setError("there is a cycle in linker script INCLUDEs");
385 if (std::optional
<std::string
> path
= searchScript(tok
)) {
386 if (std::optional
<MemoryBufferRef
> mb
= readFile(*path
))
390 setError("cannot find linker script " + tok
);
393 void ScriptParser::readInput() {
395 while (!errorCount() && !consume(")")) {
396 if (consume("AS_NEEDED"))
399 addFile(unquote(next()));
403 void ScriptParser::readOutput() {
404 // -o <file> takes predecence over OUTPUT(<file>).
406 StringRef tok
= next();
407 if (config
->outputFile
.empty())
408 config
->outputFile
= unquote(tok
);
412 void ScriptParser::readOutputArch() {
413 // OUTPUT_ARCH is ignored for now.
415 while (!errorCount() && !consume(")"))
419 static std::pair
<ELFKind
, uint16_t> parseBfdName(StringRef s
) {
420 return StringSwitch
<std::pair
<ELFKind
, uint16_t>>(s
)
421 .Case("elf32-i386", {ELF32LEKind
, EM_386
})
422 .Case("elf32-avr", {ELF32LEKind
, EM_AVR
})
423 .Case("elf32-iamcu", {ELF32LEKind
, EM_IAMCU
})
424 .Case("elf32-littlearm", {ELF32LEKind
, EM_ARM
})
425 .Case("elf32-bigarm", {ELF32BEKind
, EM_ARM
})
426 .Case("elf32-x86-64", {ELF32LEKind
, EM_X86_64
})
427 .Case("elf64-aarch64", {ELF64LEKind
, EM_AARCH64
})
428 .Case("elf64-littleaarch64", {ELF64LEKind
, EM_AARCH64
})
429 .Case("elf64-bigaarch64", {ELF64BEKind
, EM_AARCH64
})
430 .Case("elf32-powerpc", {ELF32BEKind
, EM_PPC
})
431 .Case("elf32-powerpcle", {ELF32LEKind
, EM_PPC
})
432 .Case("elf64-powerpc", {ELF64BEKind
, EM_PPC64
})
433 .Case("elf64-powerpcle", {ELF64LEKind
, EM_PPC64
})
434 .Case("elf64-x86-64", {ELF64LEKind
, EM_X86_64
})
435 .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind
, EM_MIPS
})
436 .Case("elf32-ntradbigmips", {ELF32BEKind
, EM_MIPS
})
437 .Case("elf32-tradlittlemips", {ELF32LEKind
, EM_MIPS
})
438 .Case("elf32-ntradlittlemips", {ELF32LEKind
, EM_MIPS
})
439 .Case("elf64-tradbigmips", {ELF64BEKind
, EM_MIPS
})
440 .Case("elf64-tradlittlemips", {ELF64LEKind
, EM_MIPS
})
441 .Case("elf32-littleriscv", {ELF32LEKind
, EM_RISCV
})
442 .Case("elf64-littleriscv", {ELF64LEKind
, EM_RISCV
})
443 .Case("elf64-sparc", {ELF64BEKind
, EM_SPARCV9
})
444 .Case("elf32-msp430", {ELF32LEKind
, EM_MSP430
})
445 .Case("elf32-loongarch", {ELF32LEKind
, EM_LOONGARCH
})
446 .Case("elf64-loongarch", {ELF64LEKind
, EM_LOONGARCH
})
447 .Default({ELFNoneKind
, EM_NONE
});
450 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
451 // big if -EB is specified, little if -EL is specified, or default if neither is
453 void ScriptParser::readOutputFormat() {
457 config
->bfdname
= unquote(next());
470 if (s
.consume_back("-freebsd"))
471 config
->osabi
= ELFOSABI_FREEBSD
;
473 std::tie(config
->ekind
, config
->emachine
) = parseBfdName(s
);
474 if (config
->emachine
== EM_NONE
)
475 setError("unknown output format name: " + config
->bfdname
);
476 if (s
== "elf32-ntradlittlemips" || s
== "elf32-ntradbigmips")
477 config
->mipsN32Abi
= true;
478 if (config
->emachine
== EM_MSP430
)
479 config
->osabi
= ELFOSABI_STANDALONE
;
482 void ScriptParser::readPhdrs() {
485 while (!errorCount() && !consume("}")) {
488 cmd
.type
= readPhdrType();
490 while (!errorCount() && !consume(";")) {
491 if (consume("FILEHDR"))
492 cmd
.hasFilehdr
= true;
493 else if (consume("PHDRS"))
495 else if (consume("AT"))
496 cmd
.lmaExpr
= readParenExpr();
497 else if (consume("FLAGS"))
498 cmd
.flags
= readParenExpr()().getValue();
500 setError("unexpected header attribute: " + next());
503 script
->phdrsCommands
.push_back(cmd
);
507 void ScriptParser::readRegionAlias() {
509 StringRef alias
= unquote(next());
511 StringRef name
= next();
514 if (script
->memoryRegions
.count(alias
))
515 setError("redefinition of memory region '" + alias
+ "'");
516 if (!script
->memoryRegions
.count(name
))
517 setError("memory region '" + name
+ "' is not defined");
518 script
->memoryRegions
.insert({alias
, script
->memoryRegions
[name
]});
521 void ScriptParser::readSearchDir() {
523 StringRef tok
= next();
524 if (!config
->nostdlib
)
525 config
->searchPaths
.push_back(unquote(tok
));
529 // This reads an overlay description. Overlays are used to describe output
530 // sections that use the same virtual memory range and normally would trigger
531 // linker's sections sanity check failures.
532 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
533 SmallVector
<SectionCommand
*, 0> ScriptParser::readOverlay() {
534 // VA and LMA expressions are optional, though for simplicity of
535 // implementation we assume they are not. That is what OVERLAY was designed
536 // for first of all: to allow sections with overlapping VAs at different LMAs.
537 Expr addrExpr
= readExpr();
540 Expr lmaExpr
= readParenExpr();
543 SmallVector
<SectionCommand
*, 0> v
;
544 OutputSection
*prev
= nullptr;
545 while (!errorCount() && !consume("}")) {
546 // VA is the same for all sections. The LMAs are consecutive in memory
547 // starting from the base load address specified.
548 OutputDesc
*osd
= readOverlaySectionDescription();
549 osd
->osec
.addrExpr
= addrExpr
;
551 osd
->osec
.lmaExpr
= [=] { return prev
->getLMA() + prev
->size
; };
553 osd
->osec
.lmaExpr
= lmaExpr
;
558 // According to the specification, at the end of the overlay, the location
559 // counter should be equal to the overlay base address plus size of the
560 // largest section seen in the overlay.
561 // Here we want to create the Dot assignment command to achieve that.
564 for (SectionCommand
*cmd
: v
)
565 max
= std::max(max
, cast
<OutputDesc
>(cmd
)->osec
.size
);
566 return addrExpr().getValue() + max
;
568 v
.push_back(make
<SymbolAssignment
>(".", moveDot
, 0, getCurrentLocation()));
572 void ScriptParser::readOverwriteSections() {
574 while (!errorCount() && !consume("}"))
575 script
->overwriteSections
.push_back(readOutputSectionDescription(next()));
578 void ScriptParser::readSections() {
580 SmallVector
<SectionCommand
*, 0> v
;
581 while (!errorCount() && !consume("}")) {
582 StringRef tok
= next();
583 if (tok
== "OVERLAY") {
584 for (SectionCommand
*cmd
: readOverlay())
587 } else if (tok
== "INCLUDE") {
592 if (SectionCommand
*cmd
= readAssignment(tok
))
595 v
.push_back(readOutputSectionDescription(tok
));
598 // If DATA_SEGMENT_RELRO_END is absent, for sections after DATA_SEGMENT_ALIGN,
599 // the relro fields should be cleared.
600 if (!script
->seenRelroEnd
)
601 for (SectionCommand
*cmd
: v
)
602 if (auto *osd
= dyn_cast
<OutputDesc
>(cmd
))
603 osd
->osec
.relro
= false;
605 script
->sectionCommands
.insert(script
->sectionCommands
.end(), v
.begin(),
608 if (atEOF() || !consume("INSERT")) {
609 script
->hasSectionsCommand
= true;
613 bool isAfter
= false;
614 if (consume("AFTER"))
616 else if (!consume("BEFORE"))
617 setError("expected AFTER/BEFORE, but got '" + next() + "'");
618 StringRef where
= next();
619 SmallVector
<StringRef
, 0> names
;
620 for (SectionCommand
*cmd
: v
)
621 if (auto *os
= dyn_cast
<OutputDesc
>(cmd
))
622 names
.push_back(os
->osec
.name
);
624 script
->insertCommands
.push_back({std::move(names
), isAfter
, where
});
627 void ScriptParser::readTarget() {
628 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
629 // we accept only a limited set of BFD names (i.e. "elf" or "binary")
630 // for --format. We recognize only /^elf/ and "binary" in the linker
633 StringRef tok
= unquote(next());
636 if (tok
.starts_with("elf"))
637 config
->formatBinary
= false;
638 else if (tok
== "binary")
639 config
->formatBinary
= true;
641 setError("unknown target: " + tok
);
644 static int precedence(StringRef op
) {
645 return StringSwitch
<int>(op
)
646 .Cases("*", "/", "%", 11)
648 .Cases("<<", ">>", 9)
649 .Cases("<", "<=", ">", ">=", 8)
650 .Cases("==", "!=", 7)
660 StringMatcher
ScriptParser::readFilePatterns() {
661 StringMatcher Matcher
;
663 while (!errorCount() && !consume(")"))
664 Matcher
.addPattern(SingleStringMatcher(next()));
668 SortSectionPolicy
ScriptParser::peekSortKind() {
669 return StringSwitch
<SortSectionPolicy
>(peek())
670 .Case("REVERSE", SortSectionPolicy::Reverse
)
671 .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name
)
672 .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment
)
673 .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority
)
674 .Case("SORT_NONE", SortSectionPolicy::None
)
675 .Default(SortSectionPolicy::Default
);
678 SortSectionPolicy
ScriptParser::readSortKind() {
679 SortSectionPolicy ret
= peekSortKind();
680 if (ret
!= SortSectionPolicy::Default
)
685 // Reads SECTIONS command contents in the following form:
687 // <contents> ::= <elem>*
688 // <elem> ::= <exclude>? <glob-pattern>
689 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
693 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
695 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
696 // The semantics of that is section .foo in any file, section .bar in
697 // any file but a.o, and section .baz in any file but b.o.
698 SmallVector
<SectionPattern
, 0> ScriptParser::readInputSectionsList() {
699 SmallVector
<SectionPattern
, 0> ret
;
700 while (!errorCount() && peek() != ")") {
701 StringMatcher excludeFilePat
;
702 if (consume("EXCLUDE_FILE")) {
704 excludeFilePat
= readFilePatterns();
707 StringMatcher SectionMatcher
;
708 // Break if the next token is ), EXCLUDE_FILE, or SORT*.
709 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" &&
710 peekSortKind() == SortSectionPolicy::Default
)
711 SectionMatcher
.addPattern(unquote(next()));
713 if (!SectionMatcher
.empty())
714 ret
.push_back({std::move(excludeFilePat
), std::move(SectionMatcher
)});
715 else if (excludeFilePat
.empty())
718 setError("section pattern is expected");
723 // Reads contents of "SECTIONS" directive. That directive contains a
724 // list of glob patterns for input sections. The grammar is as follows.
726 // <patterns> ::= <section-list>
727 // | <sort> "(" <section-list> ")"
728 // | <sort> "(" <sort> "(" <section-list> ")" ")"
730 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
731 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
733 // <section-list> is parsed by readInputSectionsList().
734 InputSectionDescription
*
735 ScriptParser::readInputSectionRules(StringRef filePattern
, uint64_t withFlags
,
736 uint64_t withoutFlags
) {
738 make
<InputSectionDescription
>(filePattern
, withFlags
, withoutFlags
);
741 while (!errorCount() && !consume(")")) {
742 SortSectionPolicy outer
= readSortKind();
743 SortSectionPolicy inner
= SortSectionPolicy::Default
;
744 SmallVector
<SectionPattern
, 0> v
;
745 if (outer
!= SortSectionPolicy::Default
) {
747 inner
= readSortKind();
748 if (inner
!= SortSectionPolicy::Default
) {
750 v
= readInputSectionsList();
753 v
= readInputSectionsList();
757 v
= readInputSectionsList();
760 for (SectionPattern
&pat
: v
) {
761 pat
.sortInner
= inner
;
762 pat
.sortOuter
= outer
;
765 std::move(v
.begin(), v
.end(), std::back_inserter(cmd
->sectionPatterns
));
770 InputSectionDescription
*
771 ScriptParser::readInputSectionDescription(StringRef tok
) {
772 // Input section wildcard can be surrounded by KEEP.
773 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
774 uint64_t withFlags
= 0;
775 uint64_t withoutFlags
= 0;
778 if (consume("INPUT_SECTION_FLAGS"))
779 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
780 InputSectionDescription
*cmd
=
781 readInputSectionRules(next(), withFlags
, withoutFlags
);
783 script
->keptSections
.push_back(cmd
);
786 if (tok
== "INPUT_SECTION_FLAGS") {
787 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
790 return readInputSectionRules(tok
, withFlags
, withoutFlags
);
793 void ScriptParser::readSort() {
795 expect("CONSTRUCTORS");
799 Expr
ScriptParser::readAssert() {
803 StringRef msg
= unquote(next());
809 return script
->getDot();
815 constexpr std::pair
<const char *, unsigned> typeMap
[] = {
816 ECase(SHT_PROGBITS
), ECase(SHT_NOTE
), ECase(SHT_NOBITS
),
817 ECase(SHT_INIT_ARRAY
), ECase(SHT_FINI_ARRAY
), ECase(SHT_PREINIT_ARRAY
),
821 // Tries to read the special directive for an output section definition which
822 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
824 // Tok1 and Tok2 are next 2 tokens peeked. See comment for
825 // readSectionAddressType below.
826 bool ScriptParser::readSectionDirective(OutputSection
*cmd
, StringRef tok1
, StringRef tok2
) {
829 if (tok2
!= "NOLOAD" && tok2
!= "COPY" && tok2
!= "INFO" &&
830 tok2
!= "OVERLAY" && tok2
!= "TYPE")
834 if (consume("NOLOAD")) {
835 cmd
->type
= SHT_NOBITS
;
836 cmd
->typeIsSet
= true;
837 } else if (consume("TYPE")) {
839 StringRef value
= peek();
840 auto it
= llvm::find_if(typeMap
, [=](auto e
) { return e
.first
== value
; });
841 if (it
!= std::end(typeMap
)) {
842 // The value is a recognized literal SHT_*.
843 cmd
->type
= it
->second
;
845 } else if (value
.starts_with("SHT_")) {
846 setError("unknown section type " + value
);
848 // Otherwise, read an expression.
849 cmd
->type
= readExpr()().getValue();
851 cmd
->typeIsSet
= true;
853 skip(); // This is "COPY", "INFO" or "OVERLAY".
854 cmd
->nonAlloc
= true;
860 // Reads an expression and/or the special directive for an output
861 // section definition. Directive is one of following: "(NOLOAD)",
862 // "(COPY)", "(INFO)" or "(OVERLAY)".
864 // An output section name can be followed by an address expression
865 // and/or directive. This grammar is not LL(1) because "(" can be
866 // interpreted as either the beginning of some expression or beginning
869 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
870 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
871 void ScriptParser::readSectionAddressType(OutputSection
*cmd
) {
872 // Temporarily set inExpr to support TYPE=<value> without spaces.
873 bool saved
= std::exchange(inExpr
, true);
874 bool isDirective
= readSectionDirective(cmd
, peek(), peek2());
879 cmd
->addrExpr
= readExpr();
880 if (peek() == "(" && !readSectionDirective(cmd
, "(", peek2()))
881 setError("unknown section directive: " + peek2());
884 static Expr
checkAlignment(Expr e
, std::string
&loc
) {
886 uint64_t alignment
= std::max((uint64_t)1, e().getValue());
887 if (!isPowerOf2_64(alignment
)) {
888 error(loc
+ ": alignment must be power of 2");
889 return (uint64_t)1; // Return a dummy value.
895 OutputDesc
*ScriptParser::readOverlaySectionDescription() {
896 OutputDesc
*osd
= script
->createOutputSection(next(), getCurrentLocation());
897 osd
->osec
.inOverlay
= true;
899 while (!errorCount() && !consume("}")) {
900 uint64_t withFlags
= 0;
901 uint64_t withoutFlags
= 0;
902 if (consume("INPUT_SECTION_FLAGS"))
903 std::tie(withFlags
, withoutFlags
) = readInputSectionFlags();
904 osd
->osec
.commands
.push_back(
905 readInputSectionRules(next(), withFlags
, withoutFlags
));
907 osd
->osec
.phdrs
= readOutputSectionPhdrs();
911 OutputDesc
*ScriptParser::readOutputSectionDescription(StringRef outSec
) {
913 script
->createOutputSection(unquote(outSec
), getCurrentLocation());
914 OutputSection
*osec
= &cmd
->osec
;
915 // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.
916 osec
->relro
= script
->seenDataAlign
&& !script
->seenRelroEnd
;
918 size_t symbolsReferenced
= script
->referencedSymbols
.size();
921 readSectionAddressType(osec
);
924 std::string location
= getCurrentLocation();
926 osec
->lmaExpr
= readParenExpr();
927 if (consume("ALIGN"))
928 osec
->alignExpr
= checkAlignment(readParenExpr(), location
);
929 if (consume("SUBALIGN"))
930 osec
->subalignExpr
= checkAlignment(readParenExpr(), location
);
932 // Parse constraints.
933 if (consume("ONLY_IF_RO"))
934 osec
->constraint
= ConstraintKind::ReadOnly
;
935 if (consume("ONLY_IF_RW"))
936 osec
->constraint
= ConstraintKind::ReadWrite
;
939 while (!errorCount() && !consume("}")) {
940 StringRef tok
= next();
942 // Empty commands are allowed. Do nothing here.
943 } else if (SymbolAssignment
*assign
= readAssignment(tok
)) {
944 osec
->commands
.push_back(assign
);
945 } else if (ByteCommand
*data
= readByteCommand(tok
)) {
946 osec
->commands
.push_back(data
);
947 } else if (tok
== "CONSTRUCTORS") {
948 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
949 // by name. This is for very old file formats such as ECOFF/XCOFF.
950 // For ELF, we should ignore.
951 } else if (tok
== "FILL") {
952 // We handle the FILL command as an alias for =fillexp section attribute,
953 // which is different from what GNU linkers do.
954 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
956 setError("( expected, but got " + peek());
957 osec
->filler
= readFill();
958 } else if (tok
== "SORT") {
960 } else if (tok
== "INCLUDE") {
962 } else if (tok
== "(" || tok
== ")") {
963 setError("expected filename pattern");
964 } else if (peek() == "(") {
965 osec
->commands
.push_back(readInputSectionDescription(tok
));
967 // We have a file name and no input sections description. It is not a
968 // commonly used syntax, but still acceptable. In that case, all sections
969 // from the file will be included.
970 // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
971 // handle this case here as it will already have been matched by the
973 auto *isd
= make
<InputSectionDescription
>(tok
);
974 isd
->sectionPatterns
.push_back({{}, StringMatcher("*")});
975 osec
->commands
.push_back(isd
);
980 osec
->memoryRegionName
= std::string(next());
984 osec
->lmaRegionName
= std::string(next());
987 if (osec
->lmaExpr
&& !osec
->lmaRegionName
.empty())
988 error("section can't have both LMA and a load region");
990 osec
->phdrs
= readOutputSectionPhdrs();
992 if (peek() == "=" || peek().starts_with("=")) {
995 osec
->filler
= readFill();
999 // Consume optional comma following output section command.
1002 if (script
->referencedSymbols
.size() > symbolsReferenced
)
1003 osec
->expressionsUseSymbols
= true;
1007 // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
1008 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1009 // We do not support using symbols in such expressions.
1011 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
1012 // size, while ld.gold always handles it as a 32-bit big-endian number.
1013 // We are compatible with ld.gold because it's easier to implement.
1014 // Also, we require that expressions with operators must be wrapped into
1015 // round brackets. We did it to resolve the ambiguity when parsing scripts like:
1016 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
1017 std::array
<uint8_t, 4> ScriptParser::readFill() {
1018 uint64_t value
= readPrimary()().val
;
1019 if (value
> UINT32_MAX
)
1020 setError("filler expression result does not fit 32-bit: 0x" +
1021 Twine::utohexstr(value
));
1023 std::array
<uint8_t, 4> buf
;
1024 write32be(buf
.data(), (uint32_t)value
);
1028 SymbolAssignment
*ScriptParser::readProvideHidden(bool provide
, bool hidden
) {
1030 StringRef name
= next(), eq
= peek();
1032 setError("= expected, but got " + next());
1033 while (!atEOF() && next() != ")")
1037 SymbolAssignment
*cmd
= readSymbolAssignment(name
);
1038 cmd
->provide
= provide
;
1039 cmd
->hidden
= hidden
;
1044 SymbolAssignment
*ScriptParser::readAssignment(StringRef tok
) {
1045 // Assert expression returns Dot, so this is equal to ".=."
1046 if (tok
== "ASSERT")
1047 return make
<SymbolAssignment
>(".", readAssert(), 0, getCurrentLocation());
1049 size_t oldPos
= pos
;
1050 SymbolAssignment
*cmd
= nullptr;
1051 bool savedSeenRelroEnd
= script
->seenRelroEnd
;
1052 const StringRef op
= peek();
1053 if (op
.starts_with("=")) {
1054 // Support = followed by an expression without whitespace.
1055 SaveAndRestore
saved(inExpr
, true);
1056 cmd
= readSymbolAssignment(tok
);
1057 } else if ((op
.size() == 2 && op
[1] == '=' && strchr("*/+-&^|", op
[0])) ||
1058 op
== "<<=" || op
== ">>=") {
1059 cmd
= readSymbolAssignment(tok
);
1060 } else if (tok
== "PROVIDE") {
1061 SaveAndRestore
saved(inExpr
, true);
1062 cmd
= readProvideHidden(true, false);
1063 } else if (tok
== "HIDDEN") {
1064 SaveAndRestore
saved(inExpr
, true);
1065 cmd
= readProvideHidden(false, true);
1066 } else if (tok
== "PROVIDE_HIDDEN") {
1067 SaveAndRestore
saved(inExpr
, true);
1068 cmd
= readProvideHidden(true, true);
1072 cmd
->dataSegmentRelroEnd
= !savedSeenRelroEnd
&& script
->seenRelroEnd
;
1073 cmd
->commandString
=
1075 llvm::join(tokens
.begin() + oldPos
, tokens
.begin() + pos
, " ");
1081 SymbolAssignment
*ScriptParser::readSymbolAssignment(StringRef name
) {
1082 name
= unquote(name
);
1083 StringRef op
= next();
1084 assert(op
== "=" || op
== "*=" || op
== "/=" || op
== "+=" || op
== "-=" ||
1085 op
== "&=" || op
== "^=" || op
== "|=" || op
== "<<=" || op
== ">>=");
1086 // Note: GNU ld does not support %=.
1087 Expr e
= readExpr();
1089 std::string loc
= getCurrentLocation();
1090 e
= [=, c
= op
[0]]() -> ExprValue
{
1091 ExprValue lhs
= script
->getSymbolValue(name
, loc
);
1094 return lhs
.getValue() * e().getValue();
1096 if (uint64_t rv
= e().getValue())
1097 return lhs
.getValue() / rv
;
1098 error(loc
+ ": division by zero");
1101 return add(lhs
, e());
1103 return sub(lhs
, e());
1105 return lhs
.getValue() << e().getValue() % 64;
1107 return lhs
.getValue() >> e().getValue() % 64;
1109 return lhs
.getValue() & e().getValue();
1111 return lhs
.getValue() ^ e().getValue();
1113 return lhs
.getValue() | e().getValue();
1115 llvm_unreachable("");
1119 return make
<SymbolAssignment
>(name
, e
, ctx
.scriptSymOrderCounter
++,
1120 getCurrentLocation());
1123 // This is an operator-precedence parser to parse a linker
1124 // script expression.
1125 Expr
ScriptParser::readExpr() {
1126 // Our lexer is context-aware. Set the in-expression bit so that
1127 // they apply different tokenization rules.
1130 Expr e
= readExpr1(readPrimary(), 0);
1135 Expr
ScriptParser::combine(StringRef op
, Expr l
, Expr r
) {
1137 return [=] { return add(l(), r()); };
1139 return [=] { return sub(l(), r()); };
1141 return [=] { return l().getValue() * r().getValue(); };
1143 std::string loc
= getCurrentLocation();
1144 return [=]() -> uint64_t {
1145 if (uint64_t rv
= r().getValue())
1146 return l().getValue() / rv
;
1147 error(loc
+ ": division by zero");
1152 std::string loc
= getCurrentLocation();
1153 return [=]() -> uint64_t {
1154 if (uint64_t rv
= r().getValue())
1155 return l().getValue() % rv
;
1156 error(loc
+ ": modulo by zero");
1161 return [=] { return l().getValue() << r().getValue() % 64; };
1163 return [=] { return l().getValue() >> r().getValue() % 64; };
1165 return [=] { return l().getValue() < r().getValue(); };
1167 return [=] { return l().getValue() > r().getValue(); };
1169 return [=] { return l().getValue() >= r().getValue(); };
1171 return [=] { return l().getValue() <= r().getValue(); };
1173 return [=] { return l().getValue() == r().getValue(); };
1175 return [=] { return l().getValue() != r().getValue(); };
1177 return [=] { return l().getValue() || r().getValue(); };
1179 return [=] { return l().getValue() && r().getValue(); };
1181 return [=] { return bitAnd(l(), r()); };
1183 return [=] { return bitXor(l(), r()); };
1185 return [=] { return bitOr(l(), r()); };
1186 llvm_unreachable("invalid operator");
1189 // This is a part of the operator-precedence parser. This function
1190 // assumes that the remaining token stream starts with an operator.
1191 Expr
ScriptParser::readExpr1(Expr lhs
, int minPrec
) {
1192 while (!atEOF() && !errorCount()) {
1193 // Read an operator and an expression.
1194 StringRef op1
= peek();
1195 if (precedence(op1
) < minPrec
)
1198 return readTernary(lhs
);
1200 Expr rhs
= readPrimary();
1202 // Evaluate the remaining part of the expression first if the
1203 // next operator has greater precedence than the previous one.
1204 // For example, if we have read "+" and "3", and if the next
1205 // operator is "*", then we'll evaluate 3 * ... part first.
1207 StringRef op2
= peek();
1208 if (precedence(op2
) <= precedence(op1
))
1210 rhs
= readExpr1(rhs
, precedence(op2
));
1213 lhs
= combine(op1
, lhs
, rhs
);
1218 Expr
ScriptParser::getPageSize() {
1219 std::string location
= getCurrentLocation();
1220 return [=]() -> uint64_t {
1222 return config
->commonPageSize
;
1223 error(location
+ ": unable to calculate page size");
1224 return 4096; // Return a dummy value.
1228 Expr
ScriptParser::readConstant() {
1229 StringRef s
= readParenLiteral();
1230 if (s
== "COMMONPAGESIZE")
1231 return getPageSize();
1232 if (s
== "MAXPAGESIZE")
1233 return [] { return config
->maxPageSize
; };
1234 setError("unknown constant: " + s
);
1235 return [] { return 0; };
1238 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1239 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1240 // have "K" (Ki) or "M" (Mi) suffixes.
1241 static std::optional
<uint64_t> parseInt(StringRef tok
) {
1244 if (tok
.starts_with_insensitive("0x")) {
1245 if (!to_integer(tok
.substr(2), val
, 16))
1246 return std::nullopt
;
1249 if (tok
.ends_with_insensitive("H")) {
1250 if (!to_integer(tok
.drop_back(), val
, 16))
1251 return std::nullopt
;
1256 if (tok
.ends_with_insensitive("K")) {
1257 if (!to_integer(tok
.drop_back(), val
, 10))
1258 return std::nullopt
;
1261 if (tok
.ends_with_insensitive("M")) {
1262 if (!to_integer(tok
.drop_back(), val
, 10))
1263 return std::nullopt
;
1264 return val
* 1024 * 1024;
1266 if (!to_integer(tok
, val
, 10))
1267 return std::nullopt
;
1271 ByteCommand
*ScriptParser::readByteCommand(StringRef tok
) {
1272 int size
= StringSwitch
<int>(tok
)
1281 size_t oldPos
= pos
;
1282 Expr e
= readParenExpr();
1283 std::string commandString
=
1285 llvm::join(tokens
.begin() + oldPos
, tokens
.begin() + pos
, " ");
1286 return make
<ByteCommand
>(e
, size
, commandString
);
1289 static std::optional
<uint64_t> parseFlag(StringRef tok
) {
1290 if (std::optional
<uint64_t> asInt
= parseInt(tok
))
1292 #define CASE_ENT(enum) #enum, ELF::enum
1293 return StringSwitch
<std::optional
<uint64_t>>(tok
)
1294 .Case(CASE_ENT(SHF_WRITE
))
1295 .Case(CASE_ENT(SHF_ALLOC
))
1296 .Case(CASE_ENT(SHF_EXECINSTR
))
1297 .Case(CASE_ENT(SHF_MERGE
))
1298 .Case(CASE_ENT(SHF_STRINGS
))
1299 .Case(CASE_ENT(SHF_INFO_LINK
))
1300 .Case(CASE_ENT(SHF_LINK_ORDER
))
1301 .Case(CASE_ENT(SHF_OS_NONCONFORMING
))
1302 .Case(CASE_ENT(SHF_GROUP
))
1303 .Case(CASE_ENT(SHF_TLS
))
1304 .Case(CASE_ENT(SHF_COMPRESSED
))
1305 .Case(CASE_ENT(SHF_EXCLUDE
))
1306 .Case(CASE_ENT(SHF_ARM_PURECODE
))
1307 .Default(std::nullopt
);
1311 // Reads the '(' <flags> ')' list of section flags in
1312 // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1314 // <flags> ::= <flag>
1316 // <flag> ::= Recognized Flag Name, or Integer value of flag.
1317 // If the first character of <flag> is a ! then this means without flag,
1318 // otherwise with flag.
1319 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1320 // without flag SHF_WRITE.
1321 std::pair
<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1322 uint64_t withFlags
= 0;
1323 uint64_t withoutFlags
= 0;
1325 while (!errorCount()) {
1326 StringRef tok
= unquote(next());
1327 bool without
= tok
.consume_front("!");
1328 if (std::optional
<uint64_t> flag
= parseFlag(tok
)) {
1330 withoutFlags
|= *flag
;
1334 setError("unrecognised flag: " + tok
);
1338 if (!consume("&")) {
1340 setError("expected & or )");
1343 return std::make_pair(withFlags
, withoutFlags
);
1346 StringRef
ScriptParser::readParenLiteral() {
1350 StringRef tok
= next();
1356 static void checkIfExists(const OutputSection
&osec
, StringRef location
) {
1357 if (osec
.location
.empty() && script
->errorOnMissingSection
)
1358 error(location
+ ": undefined section " + osec
.name
);
1361 static bool isValidSymbolName(StringRef s
) {
1362 auto valid
= [](char c
) {
1363 return isAlnum(c
) || c
== '$' || c
== '.' || c
== '_';
1365 return !s
.empty() && !isDigit(s
[0]) && llvm::all_of(s
, valid
);
1368 Expr
ScriptParser::readPrimary() {
1370 return readParenExpr();
1373 Expr e
= readPrimary();
1374 return [=] { return ~e().getValue(); };
1377 Expr e
= readPrimary();
1378 return [=] { return !e().getValue(); };
1381 Expr e
= readPrimary();
1382 return [=] { return -e().getValue(); };
1385 StringRef tok
= next();
1386 std::string location
= getCurrentLocation();
1388 // Built-in functions are parsed here.
1389 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1390 if (tok
== "ABSOLUTE") {
1391 Expr inner
= readParenExpr();
1393 ExprValue i
= inner();
1394 i
.forceAbsolute
= true;
1398 if (tok
== "ADDR") {
1399 StringRef name
= unquote(readParenLiteral());
1400 OutputSection
*osec
= &script
->getOrCreateOutputSection(name
)->osec
;
1401 osec
->usedInExpression
= true;
1402 return [=]() -> ExprValue
{
1403 checkIfExists(*osec
, location
);
1404 return {osec
, false, 0, location
};
1407 if (tok
== "ALIGN") {
1409 Expr e
= readExpr();
1411 e
= checkAlignment(e
, location
);
1412 return [=] { return alignToPowerOf2(script
->getDot(), e().getValue()); };
1415 Expr e2
= checkAlignment(readExpr(), location
);
1419 v
.alignment
= e2().getValue();
1423 if (tok
== "ALIGNOF") {
1424 StringRef name
= unquote(readParenLiteral());
1425 OutputSection
*osec
= &script
->getOrCreateOutputSection(name
)->osec
;
1427 checkIfExists(*osec
, location
);
1428 return osec
->addralign
;
1431 if (tok
== "ASSERT")
1432 return readAssert();
1433 if (tok
== "CONSTANT")
1434 return readConstant();
1435 if (tok
== "DATA_SEGMENT_ALIGN") {
1437 Expr e
= readExpr();
1441 script
->seenDataAlign
= true;
1443 uint64_t align
= std::max(uint64_t(1), e().getValue());
1444 return (script
->getDot() + align
- 1) & -align
;
1447 if (tok
== "DATA_SEGMENT_END") {
1451 return [] { return script
->getDot(); };
1453 if (tok
== "DATA_SEGMENT_RELRO_END") {
1454 // GNU linkers implements more complicated logic to handle
1455 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1456 // just align to the next page boundary for simplicity.
1462 script
->seenRelroEnd
= true;
1463 return [=] { return alignToPowerOf2(script
->getDot(), config
->maxPageSize
); };
1465 if (tok
== "DEFINED") {
1466 StringRef name
= unquote(readParenLiteral());
1467 // Return 1 if s is defined. If the definition is only found in a linker
1468 // script, it must happen before this DEFINED.
1469 auto order
= ctx
.scriptSymOrderCounter
++;
1471 Symbol
*s
= symtab
.find(name
);
1472 return s
&& s
->isDefined() && ctx
.scriptSymOrder
.lookup(s
) < order
? 1
1476 if (tok
== "LENGTH") {
1477 StringRef name
= readParenLiteral();
1478 if (script
->memoryRegions
.count(name
) == 0) {
1479 setError("memory region not defined: " + name
);
1480 return [] { return 0; };
1482 return script
->memoryRegions
[name
]->length
;
1484 if (tok
== "LOADADDR") {
1485 StringRef name
= unquote(readParenLiteral());
1486 OutputSection
*osec
= &script
->getOrCreateOutputSection(name
)->osec
;
1487 osec
->usedInExpression
= true;
1489 checkIfExists(*osec
, location
);
1490 return osec
->getLMA();
1493 if (tok
== "LOG2CEIL") {
1495 Expr a
= readExpr();
1498 // LOG2CEIL(0) is defined to be 0.
1499 return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1502 if (tok
== "MAX" || tok
== "MIN") {
1504 Expr a
= readExpr();
1506 Expr b
= readExpr();
1509 return [=] { return std::min(a().getValue(), b().getValue()); };
1510 return [=] { return std::max(a().getValue(), b().getValue()); };
1512 if (tok
== "ORIGIN") {
1513 StringRef name
= readParenLiteral();
1514 if (script
->memoryRegions
.count(name
) == 0) {
1515 setError("memory region not defined: " + name
);
1516 return [] { return 0; };
1518 return script
->memoryRegions
[name
]->origin
;
1520 if (tok
== "SEGMENT_START") {
1524 Expr e
= readExpr();
1526 return [=] { return e(); };
1528 if (tok
== "SIZEOF") {
1529 StringRef name
= unquote(readParenLiteral());
1530 OutputSection
*cmd
= &script
->getOrCreateOutputSection(name
)->osec
;
1531 // Linker script does not create an output section if its content is empty.
1532 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1534 return [=] { return cmd
->size
; };
1536 if (tok
== "SIZEOF_HEADERS")
1537 return [=] { return elf::getHeaderSize(); };
1541 return [=] { return script
->getSymbolValue(tok
, location
); };
1543 // Tok is a literal number.
1544 if (std::optional
<uint64_t> val
= parseInt(tok
))
1545 return [=] { return *val
; };
1547 // Tok is a symbol name.
1548 if (tok
.starts_with("\""))
1550 else if (!isValidSymbolName(tok
))
1551 setError("malformed number: " + tok
);
1552 script
->referencedSymbols
.push_back(tok
);
1553 return [=] { return script
->getSymbolValue(tok
, location
); };
1556 Expr
ScriptParser::readTernary(Expr cond
) {
1557 Expr l
= readExpr();
1559 Expr r
= readExpr();
1560 return [=] { return cond().getValue() ? l() : r(); };
1563 Expr
ScriptParser::readParenExpr() {
1565 Expr e
= readExpr();
1570 SmallVector
<StringRef
, 0> ScriptParser::readOutputSectionPhdrs() {
1571 SmallVector
<StringRef
, 0> phdrs
;
1572 while (!errorCount() && peek().starts_with(":")) {
1573 StringRef tok
= next();
1574 phdrs
.push_back((tok
.size() == 1) ? next() : tok
.substr(1));
1579 // Read a program header type name. The next token must be a
1580 // name of a program header type or a constant (e.g. "0x3").
1581 unsigned ScriptParser::readPhdrType() {
1582 StringRef tok
= next();
1583 if (std::optional
<uint64_t> val
= parseInt(tok
))
1586 unsigned ret
= StringSwitch
<unsigned>(tok
)
1587 .Case("PT_NULL", PT_NULL
)
1588 .Case("PT_LOAD", PT_LOAD
)
1589 .Case("PT_DYNAMIC", PT_DYNAMIC
)
1590 .Case("PT_INTERP", PT_INTERP
)
1591 .Case("PT_NOTE", PT_NOTE
)
1592 .Case("PT_SHLIB", PT_SHLIB
)
1593 .Case("PT_PHDR", PT_PHDR
)
1594 .Case("PT_TLS", PT_TLS
)
1595 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME
)
1596 .Case("PT_GNU_STACK", PT_GNU_STACK
)
1597 .Case("PT_GNU_RELRO", PT_GNU_RELRO
)
1598 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE
)
1599 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED
)
1600 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA
)
1603 if (ret
== (unsigned)-1) {
1604 setError("invalid program header type: " + tok
);
1610 // Reads an anonymous version declaration.
1611 void ScriptParser::readAnonymousDeclaration() {
1612 SmallVector
<SymbolVersion
, 0> locals
;
1613 SmallVector
<SymbolVersion
, 0> globals
;
1614 std::tie(locals
, globals
) = readSymbols();
1615 for (const SymbolVersion
&pat
: locals
)
1616 config
->versionDefinitions
[VER_NDX_LOCAL
].localPatterns
.push_back(pat
);
1617 for (const SymbolVersion
&pat
: globals
)
1618 config
->versionDefinitions
[VER_NDX_GLOBAL
].nonLocalPatterns
.push_back(pat
);
1623 // Reads a non-anonymous version definition,
1624 // e.g. "VerStr { global: foo; bar; local: *; };".
1625 void ScriptParser::readVersionDeclaration(StringRef verStr
) {
1626 // Read a symbol list.
1627 SmallVector
<SymbolVersion
, 0> locals
;
1628 SmallVector
<SymbolVersion
, 0> globals
;
1629 std::tie(locals
, globals
) = readSymbols();
1631 // Create a new version definition and add that to the global symbols.
1632 VersionDefinition ver
;
1634 ver
.nonLocalPatterns
= std::move(globals
);
1635 ver
.localPatterns
= std::move(locals
);
1636 ver
.id
= config
->versionDefinitions
.size();
1637 config
->versionDefinitions
.push_back(ver
);
1639 // Each version may have a parent version. For example, "Ver2"
1640 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1641 // as a parent. This version hierarchy is, probably against your
1642 // instinct, purely for hint; the runtime doesn't care about it
1643 // at all. In LLD, we simply ignore it.
1648 bool elf::hasWildcard(StringRef s
) {
1649 return s
.find_first_of("?*[") != StringRef::npos
;
1652 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1653 std::pair
<SmallVector
<SymbolVersion
, 0>, SmallVector
<SymbolVersion
, 0>>
1654 ScriptParser::readSymbols() {
1655 SmallVector
<SymbolVersion
, 0> locals
;
1656 SmallVector
<SymbolVersion
, 0> globals
;
1657 SmallVector
<SymbolVersion
, 0> *v
= &globals
;
1659 while (!errorCount()) {
1662 if (consumeLabel("local")) {
1666 if (consumeLabel("global")) {
1671 if (consume("extern")) {
1672 SmallVector
<SymbolVersion
, 0> ext
= readVersionExtern();
1673 v
->insert(v
->end(), ext
.begin(), ext
.end());
1675 StringRef tok
= next();
1676 v
->push_back({unquote(tok
), false, hasWildcard(tok
)});
1680 return {locals
, globals
};
1683 // Reads an "extern C++" directive, e.g.,
1684 // "extern "C++" { ns::*; "f(int, double)"; };"
1686 // The last semicolon is optional. E.g. this is OK:
1687 // "extern "C++" { ns::*; "f(int, double)" };"
1688 SmallVector
<SymbolVersion
, 0> ScriptParser::readVersionExtern() {
1689 StringRef tok
= next();
1690 bool isCXX
= tok
== "\"C++\"";
1691 if (!isCXX
&& tok
!= "\"C\"")
1692 setError("Unknown language");
1695 SmallVector
<SymbolVersion
, 0> ret
;
1696 while (!errorCount() && peek() != "}") {
1697 StringRef tok
= next();
1699 {unquote(tok
), isCXX
, !tok
.starts_with("\"") && hasWildcard(tok
)});
1709 Expr
ScriptParser::readMemoryAssignment(StringRef s1
, StringRef s2
,
1711 if (!consume(s1
) && !consume(s2
) && !consume(s3
)) {
1712 setError("expected one of: " + s1
+ ", " + s2
+ ", or " + s3
);
1713 return [] { return 0; };
1719 // Parse the MEMORY command as specified in:
1720 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1722 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1723 void ScriptParser::readMemory() {
1725 while (!errorCount() && !consume("}")) {
1726 StringRef tok
= next();
1727 if (tok
== "INCLUDE") {
1733 uint32_t invFlags
= 0;
1734 uint32_t negFlags
= 0;
1735 uint32_t negInvFlags
= 0;
1737 readMemoryAttributes(flags
, invFlags
, negFlags
, negInvFlags
);
1742 Expr origin
= readMemoryAssignment("ORIGIN", "org", "o");
1744 Expr length
= readMemoryAssignment("LENGTH", "len", "l");
1746 // Add the memory region to the region map.
1747 MemoryRegion
*mr
= make
<MemoryRegion
>(tok
, origin
, length
, flags
, invFlags
,
1748 negFlags
, negInvFlags
);
1749 if (!script
->memoryRegions
.insert({tok
, mr
}).second
)
1750 setError("region '" + tok
+ "' already defined");
1754 // This function parses the attributes used to match against section
1755 // flags when placing output sections in a memory region. These flags
1756 // are only used when an explicit memory region name is not used.
1757 void ScriptParser::readMemoryAttributes(uint32_t &flags
, uint32_t &invFlags
,
1759 uint32_t &negInvFlags
) {
1760 bool invert
= false;
1762 for (char c
: next().lower()) {
1765 std::swap(flags
, negFlags
);
1766 std::swap(invFlags
, negInvFlags
);
1772 flags
|= SHF_EXECINSTR
;
1776 invFlags
|= SHF_WRITE
;
1778 setError("invalid memory region attribute");
1782 std::swap(flags
, negFlags
);
1783 std::swap(invFlags
, negInvFlags
);
1787 void elf::readLinkerScript(MemoryBufferRef mb
) {
1788 llvm::TimeTraceScope
timeScope("Read linker script",
1789 mb
.getBufferIdentifier());
1790 ScriptParser(mb
).readLinkerScript();
1793 void elf::readVersionScript(MemoryBufferRef mb
) {
1794 llvm::TimeTraceScope
timeScope("Read version script",
1795 mb
.getBufferIdentifier());
1796 ScriptParser(mb
).readVersionScript();
1799 void elf::readDynamicList(MemoryBufferRef mb
) {
1800 llvm::TimeTraceScope
timeScope("Read dynamic list", mb
.getBufferIdentifier());
1801 ScriptParser(mb
).readDynamicList();
1804 void elf::readDefsym(StringRef name
, MemoryBufferRef mb
) {
1805 llvm::TimeTraceScope
timeScope("Read defsym input", name
);
1806 ScriptParser(mb
).readDefsym(name
);