1 //===- ScriptParser.cpp ---------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a recursive-descendent parser for linker scripts.
11 // Parsed results are stored to Config and Script global objects.
13 //===----------------------------------------------------------------------===//
15 #include "ScriptParser.h"
18 #include "InputSection.h"
19 #include "LinkerScript.h"
20 #include "OutputSections.h"
21 #include "ScriptLexer.h"
24 #include "lld/Common/Memory.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/Path.h"
39 using namespace llvm::ELF;
40 using namespace llvm::support::endian;
42 using namespace lld::elf;
44 static bool isUnderSysroot(StringRef Path);
47 class ScriptParser final : ScriptLexer {
49 ScriptParser(MemoryBufferRef MB)
51 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
53 void readLinkerScript();
54 void readVersionScript();
55 void readDynamicList();
56 void readDefsym(StringRef Name);
59 void addFile(StringRef Path);
69 void readOutputArch();
70 void readOutputFormat();
72 void readRegionAlias();
77 void readVersionScriptCommand();
79 SymbolAssignment *readSymbolAssignment(StringRef Name);
80 ByteCommand *readByteCommand(StringRef Tok);
81 std::array<uint8_t, 4> readFill();
82 std::array<uint8_t, 4> parseFill(StringRef Tok);
83 bool readSectionDirective(OutputSection *Cmd, StringRef Tok1, StringRef Tok2);
84 void readSectionAddressType(OutputSection *Cmd);
85 OutputSection *readOverlaySectionDescription();
86 OutputSection *readOutputSectionDescription(StringRef OutSec);
87 std::vector<BaseCommand *> readOverlay();
88 std::vector<StringRef> readOutputSectionPhdrs();
89 InputSectionDescription *readInputSectionDescription(StringRef Tok);
90 StringMatcher readFilePatterns();
91 std::vector<SectionPattern> readInputSectionsList();
92 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
93 unsigned readPhdrType();
94 SortSectionPolicy readSortKind();
95 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
96 SymbolAssignment *readAssignment(StringRef Tok);
102 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
103 std::pair<uint32_t, uint32_t> readMemoryAttributes();
105 Expr combine(StringRef Op, Expr L, Expr R);
107 Expr readExpr1(Expr Lhs, int MinPrec);
108 StringRef readParenLiteral();
110 Expr readTernary(Expr Cond);
111 Expr readParenExpr();
113 // For parsing version script.
114 std::vector<SymbolVersion> readVersionExtern();
115 void readAnonymousDeclaration();
116 void readVersionDeclaration(StringRef VerStr);
118 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
121 // True if a script being read is in a subdirectory specified by -sysroot.
124 // A set to detect an INCLUDE() cycle.
129 static StringRef unquote(StringRef S) {
130 if (S.startswith("\""))
131 return S.substr(1, S.size() - 2);
135 static bool isUnderSysroot(StringRef Path) {
136 if (Config->Sysroot == "")
138 for (; !Path.empty(); Path = sys::path::parent_path(Path))
139 if (sys::fs::equivalent(Config->Sysroot, Path))
144 // Some operations only support one non absolute value. Move the
145 // absolute one to the right hand side for convenience.
146 static void moveAbsRight(ExprValue &A, ExprValue &B) {
147 if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
150 error(A.Loc + ": at least one side of the expression must be absolute");
153 static ExprValue add(ExprValue A, ExprValue 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(ExprValue A, ExprValue B) {
167 return {A.Sec, A.ForceAbsolute,
168 (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
171 static ExprValue bitOr(ExprValue A, ExprValue B) {
173 return {A.Sec, A.ForceAbsolute,
174 (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
177 void ScriptParser::readDynamicList() {
178 Config->HasDynamicList = true;
180 std::vector<SymbolVersion> Locals;
181 std::vector<SymbolVersion> Globals;
182 std::tie(Locals, Globals) = readSymbols();
186 setError("EOF expected, but got " + next());
189 if (!Locals.empty()) {
190 setError("\"local:\" scope not supported in --dynamic-list");
194 for (SymbolVersion V : Globals)
195 Config->DynamicList.push_back(V);
198 void ScriptParser::readVersionScript() {
199 readVersionScriptCommand();
201 setError("EOF expected, but got " + next());
204 void ScriptParser::readVersionScriptCommand() {
206 readAnonymousDeclaration();
210 while (!atEOF() && !errorCount() && peek() != "}") {
211 StringRef VerStr = next();
213 setError("anonymous version definition is used in "
214 "combination with other version definitions");
218 readVersionDeclaration(VerStr);
222 void ScriptParser::readVersion() {
224 readVersionScriptCommand();
228 void ScriptParser::readLinkerScript() {
230 StringRef Tok = next();
234 if (Tok == "ENTRY") {
236 } else if (Tok == "EXTERN") {
238 } else if (Tok == "GROUP") {
240 } else if (Tok == "INCLUDE") {
242 } else if (Tok == "INPUT") {
244 } else if (Tok == "MEMORY") {
246 } else if (Tok == "OUTPUT") {
248 } else if (Tok == "OUTPUT_ARCH") {
250 } else if (Tok == "OUTPUT_FORMAT") {
252 } else if (Tok == "PHDRS") {
254 } else if (Tok == "REGION_ALIAS") {
256 } else if (Tok == "SEARCH_DIR") {
258 } else if (Tok == "SECTIONS") {
260 } else if (Tok == "TARGET") {
262 } else if (Tok == "VERSION") {
264 } else if (SymbolAssignment *Cmd = readAssignment(Tok)) {
265 Script->SectionCommands.push_back(Cmd);
267 setError("unknown directive: " + Tok);
272 void ScriptParser::readDefsym(StringRef Name) {
277 setError("EOF expected, but got " + next());
278 SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
279 Script->SectionCommands.push_back(Cmd);
282 void ScriptParser::addFile(StringRef S) {
283 if (IsUnderSysroot && S.startswith("/")) {
284 SmallString<128> PathData;
285 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
286 if (sys::fs::exists(Path)) {
287 Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
292 if (S.startswith("/")) {
293 Driver->addFile(S, /*WithLOption=*/false);
294 } else if (S.startswith("=")) {
295 if (Config->Sysroot.empty())
296 Driver->addFile(S.substr(1), /*WithLOption=*/false);
298 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
299 /*WithLOption=*/false);
300 } else if (S.startswith("-l")) {
301 Driver->addLibrary(S.substr(2));
302 } else if (sys::fs::exists(S)) {
303 Driver->addFile(S, /*WithLOption=*/false);
305 if (Optional<std::string> Path = findFromSearchPaths(S))
306 Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
308 setError("unable to find " + S);
312 void ScriptParser::readAsNeeded() {
314 bool Orig = Config->AsNeeded;
315 Config->AsNeeded = true;
316 while (!errorCount() && !consume(")"))
317 addFile(unquote(next()));
318 Config->AsNeeded = Orig;
321 void ScriptParser::readEntry() {
322 // -e <symbol> takes predecence over ENTRY(<symbol>).
324 StringRef Tok = next();
325 if (Config->Entry.empty())
330 void ScriptParser::readExtern() {
332 while (!errorCount() && !consume(")"))
333 Config->Undefined.push_back(next());
336 void ScriptParser::readGroup() {
337 bool Orig = InputFile::IsInGroup;
338 InputFile::IsInGroup = true;
340 InputFile::IsInGroup = Orig;
342 ++InputFile::NextGroupId;
345 void ScriptParser::readInclude() {
346 StringRef Tok = unquote(next());
348 if (!Seen.insert(Tok).second) {
349 setError("there is a cycle in linker script INCLUDEs");
353 if (Optional<std::string> Path = searchScript(Tok)) {
354 if (Optional<MemoryBufferRef> MB = readFile(*Path))
358 setError("cannot find linker script " + Tok);
361 void ScriptParser::readInput() {
363 while (!errorCount() && !consume(")")) {
364 if (consume("AS_NEEDED"))
367 addFile(unquote(next()));
371 void ScriptParser::readOutput() {
372 // -o <file> takes predecence over OUTPUT(<file>).
374 StringRef Tok = next();
375 if (Config->OutputFile.empty())
376 Config->OutputFile = unquote(Tok);
380 void ScriptParser::readOutputArch() {
381 // OUTPUT_ARCH is ignored for now.
383 while (!errorCount() && !consume(")"))
387 static std::pair<ELFKind, uint16_t> parseBfdName(StringRef S) {
388 return StringSwitch<std::pair<ELFKind, uint16_t>>(S)
389 .Case("elf32-i386", {ELF32LEKind, EM_386})
390 .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
391 .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
392 .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
393 .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
394 .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
395 .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
396 .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
397 .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
398 .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
399 .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
400 .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
401 .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
402 .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
403 .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
404 .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
405 .Default({ELFNoneKind, EM_NONE});
408 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(bfdname, big, little).
409 // Currently we ignore big and little parameters.
410 void ScriptParser::readOutputFormat() {
413 StringRef Name = unquote(next());
415 if (S.consume_back("-freebsd"))
416 Config->OSABI = ELFOSABI_FREEBSD;
418 std::tie(Config->EKind, Config->EMachine) = parseBfdName(S);
419 if (Config->EMachine == EM_NONE)
420 setError("unknown output format name: " + Name);
421 if (S == "elf32-ntradlittlemips" || S == "elf32-ntradbigmips")
422 Config->MipsN32Abi = true;
433 void ScriptParser::readPhdrs() {
436 while (!errorCount() && !consume("}")) {
439 Cmd.Type = readPhdrType();
441 while (!errorCount() && !consume(";")) {
442 if (consume("FILEHDR"))
443 Cmd.HasFilehdr = true;
444 else if (consume("PHDRS"))
446 else if (consume("AT"))
447 Cmd.LMAExpr = readParenExpr();
448 else if (consume("FLAGS"))
449 Cmd.Flags = readParenExpr()().getValue();
451 setError("unexpected header attribute: " + next());
454 Script->PhdrsCommands.push_back(Cmd);
458 void ScriptParser::readRegionAlias() {
460 StringRef Alias = unquote(next());
462 StringRef Name = next();
465 if (Script->MemoryRegions.count(Alias))
466 setError("redefinition of memory region '" + Alias + "'");
467 if (!Script->MemoryRegions.count(Name))
468 setError("memory region '" + Name + "' is not defined");
469 Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
472 void ScriptParser::readSearchDir() {
474 StringRef Tok = next();
475 if (!Config->Nostdlib)
476 Config->SearchPaths.push_back(unquote(Tok));
480 // This reads an overlay description. Overlays are used to describe output
481 // sections that use the same virtual memory range and normally would trigger
482 // linker's sections sanity check failures.
483 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
484 std::vector<BaseCommand *> ScriptParser::readOverlay() {
485 // VA and LMA expressions are optional, though for simplicity of
486 // implementation we assume they are not. That is what OVERLAY was designed
487 // for first of all: to allow sections with overlapping VAs at different LMAs.
488 Expr AddrExpr = readExpr();
491 Expr LMAExpr = readParenExpr();
494 std::vector<BaseCommand *> V;
495 OutputSection *Prev = nullptr;
496 while (!errorCount() && !consume("}")) {
497 // VA is the same for all sections. The LMAs are consecutive in memory
498 // starting from the base load address specified.
499 OutputSection *OS = readOverlaySectionDescription();
500 OS->AddrExpr = AddrExpr;
502 OS->LMAExpr = [=] { return Prev->getLMA() + Prev->Size; };
504 OS->LMAExpr = LMAExpr;
509 // According to the specification, at the end of the overlay, the location
510 // counter should be equal to the overlay base address plus size of the
511 // largest section seen in the overlay.
512 // Here we want to create the Dot assignment command to achieve that.
515 for (BaseCommand *Cmd : V)
516 Max = std::max(Max, cast<OutputSection>(Cmd)->Size);
517 return AddrExpr().getValue() + Max;
519 V.push_back(make<SymbolAssignment>(".", MoveDot, getCurrentLocation()));
523 void ScriptParser::readSections() {
524 Script->HasSectionsCommand = true;
526 // -no-rosegment is used to avoid placing read only non-executable sections in
527 // their own segment. We do the same if SECTIONS command is present in linker
528 // script. See comment for computeFlags().
529 Config->SingleRoRx = true;
532 std::vector<BaseCommand *> V;
533 while (!errorCount() && !consume("}")) {
534 StringRef Tok = next();
535 if (Tok == "OVERLAY") {
536 for (BaseCommand *Cmd : readOverlay())
539 } else if (Tok == "INCLUDE") {
544 if (BaseCommand *Cmd = readAssignment(Tok))
547 V.push_back(readOutputSectionDescription(Tok));
550 if (!atEOF() && consume("INSERT")) {
551 std::vector<BaseCommand *> *Dest = nullptr;
552 if (consume("AFTER"))
553 Dest = &Script->InsertAfterCommands[next()];
554 else if (consume("BEFORE"))
555 Dest = &Script->InsertBeforeCommands[next()];
557 setError("expected AFTER/BEFORE, but got '" + next() + "'");
559 Dest->insert(Dest->end(), V.begin(), V.end());
563 Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(),
567 void ScriptParser::readTarget() {
568 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
569 // we accept only a limited set of BFD names (i.e. "elf" or "binary")
570 // for --format. We recognize only /^elf/ and "binary" in the linker
573 StringRef Tok = next();
576 if (Tok.startswith("elf"))
577 Config->FormatBinary = false;
578 else if (Tok == "binary")
579 Config->FormatBinary = true;
581 setError("unknown target: " + Tok);
584 static int precedence(StringRef Op) {
585 return StringSwitch<int>(Op)
586 .Cases("*", "/", "%", 8)
588 .Cases("<<", ">>", 6)
589 .Cases("<", "<=", ">", ">=", "==", "!=", 5)
597 StringMatcher ScriptParser::readFilePatterns() {
598 std::vector<StringRef> V;
599 while (!errorCount() && !consume(")"))
601 return StringMatcher(V);
604 SortSectionPolicy ScriptParser::readSortKind() {
605 if (consume("SORT") || consume("SORT_BY_NAME"))
606 return SortSectionPolicy::Name;
607 if (consume("SORT_BY_ALIGNMENT"))
608 return SortSectionPolicy::Alignment;
609 if (consume("SORT_BY_INIT_PRIORITY"))
610 return SortSectionPolicy::Priority;
611 if (consume("SORT_NONE"))
612 return SortSectionPolicy::None;
613 return SortSectionPolicy::Default;
616 // Reads SECTIONS command contents in the following form:
618 // <contents> ::= <elem>*
619 // <elem> ::= <exclude>? <glob-pattern>
620 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
624 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
626 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
627 // The semantics of that is section .foo in any file, section .bar in
628 // any file but a.o, and section .baz in any file but b.o.
629 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
630 std::vector<SectionPattern> Ret;
631 while (!errorCount() && peek() != ")") {
632 StringMatcher ExcludeFilePat;
633 if (consume("EXCLUDE_FILE")) {
635 ExcludeFilePat = readFilePatterns();
638 std::vector<StringRef> V;
639 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
643 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
645 setError("section pattern is expected");
650 // Reads contents of "SECTIONS" directive. That directive contains a
651 // list of glob patterns for input sections. The grammar is as follows.
653 // <patterns> ::= <section-list>
654 // | <sort> "(" <section-list> ")"
655 // | <sort> "(" <sort> "(" <section-list> ")" ")"
657 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
658 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
660 // <section-list> is parsed by readInputSectionsList().
661 InputSectionDescription *
662 ScriptParser::readInputSectionRules(StringRef FilePattern) {
663 auto *Cmd = make<InputSectionDescription>(FilePattern);
666 while (!errorCount() && !consume(")")) {
667 SortSectionPolicy Outer = readSortKind();
668 SortSectionPolicy Inner = SortSectionPolicy::Default;
669 std::vector<SectionPattern> V;
670 if (Outer != SortSectionPolicy::Default) {
672 Inner = readSortKind();
673 if (Inner != SortSectionPolicy::Default) {
675 V = readInputSectionsList();
678 V = readInputSectionsList();
682 V = readInputSectionsList();
685 for (SectionPattern &Pat : V) {
686 Pat.SortInner = Inner;
687 Pat.SortOuter = Outer;
690 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
695 InputSectionDescription *
696 ScriptParser::readInputSectionDescription(StringRef Tok) {
697 // Input section wildcard can be surrounded by KEEP.
698 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
701 StringRef FilePattern = next();
702 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
704 Script->KeptSections.push_back(Cmd);
707 return readInputSectionRules(Tok);
710 void ScriptParser::readSort() {
712 expect("CONSTRUCTORS");
716 Expr ScriptParser::readAssert() {
720 StringRef Msg = unquote(next());
726 return Script->getDot();
730 // Reads a FILL(expr) command. We handle the FILL command as an
731 // alias for =fillexp section attribute, which is different from
732 // what GNU linkers do.
733 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
734 std::array<uint8_t, 4> ScriptParser::readFill() {
736 std::array<uint8_t, 4> V = parseFill(next());
741 // Tries to read the special directive for an output section definition which
742 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
743 // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
744 bool ScriptParser::readSectionDirective(OutputSection *Cmd, StringRef Tok1, StringRef Tok2) {
747 if (Tok2 != "NOLOAD" && Tok2 != "COPY" && Tok2 != "INFO" && Tok2 != "OVERLAY")
751 if (consume("NOLOAD")) {
754 skip(); // This is "COPY", "INFO" or "OVERLAY".
755 Cmd->NonAlloc = true;
761 // Reads an expression and/or the special directive for an output
762 // section definition. Directive is one of following: "(NOLOAD)",
763 // "(COPY)", "(INFO)" or "(OVERLAY)".
765 // An output section name can be followed by an address expression
766 // and/or directive. This grammar is not LL(1) because "(" can be
767 // interpreted as either the beginning of some expression or beginning
770 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
771 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
772 void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
773 if (readSectionDirective(Cmd, peek(), peek2()))
776 Cmd->AddrExpr = readExpr();
777 if (peek() == "(" && !readSectionDirective(Cmd, "(", peek2()))
778 setError("unknown section directive: " + peek2());
781 static Expr checkAlignment(Expr E, std::string &Loc) {
783 uint64_t Alignment = std::max((uint64_t)1, E().getValue());
784 if (!isPowerOf2_64(Alignment)) {
785 error(Loc + ": alignment must be power of 2");
786 return (uint64_t)1; // Return a dummy value.
792 OutputSection *ScriptParser::readOverlaySectionDescription() {
794 Script->createOutputSection(next(), getCurrentLocation());
795 Cmd->InOverlay = true;
797 while (!errorCount() && !consume("}"))
798 Cmd->SectionCommands.push_back(readInputSectionRules(next()));
799 Cmd->Phdrs = readOutputSectionPhdrs();
803 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
805 Script->createOutputSection(OutSec, getCurrentLocation());
807 size_t SymbolsReferenced = Script->ReferencedSymbols.size();
810 readSectionAddressType(Cmd);
813 std::string Location = getCurrentLocation();
815 Cmd->LMAExpr = readParenExpr();
816 if (consume("ALIGN"))
817 Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
818 if (consume("SUBALIGN"))
819 Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
821 // Parse constraints.
822 if (consume("ONLY_IF_RO"))
823 Cmd->Constraint = ConstraintKind::ReadOnly;
824 if (consume("ONLY_IF_RW"))
825 Cmd->Constraint = ConstraintKind::ReadWrite;
828 while (!errorCount() && !consume("}")) {
829 StringRef Tok = next();
831 // Empty commands are allowed. Do nothing here.
832 } else if (SymbolAssignment *Assign = readAssignment(Tok)) {
833 Cmd->SectionCommands.push_back(Assign);
834 } else if (ByteCommand *Data = readByteCommand(Tok)) {
835 Cmd->SectionCommands.push_back(Data);
836 } else if (Tok == "CONSTRUCTORS") {
837 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
838 // by name. This is for very old file formats such as ECOFF/XCOFF.
839 // For ELF, we should ignore.
840 } else if (Tok == "FILL") {
841 Cmd->Filler = readFill();
842 } else if (Tok == "SORT") {
844 } else if (Tok == "INCLUDE") {
846 } else if (peek() == "(") {
847 Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
849 // We have a file name and no input sections description. It is not a
850 // commonly used syntax, but still acceptable. In that case, all sections
851 // from the file will be included.
852 auto *ISD = make<InputSectionDescription>(Tok);
853 ISD->SectionPatterns.push_back({{}, StringMatcher({"*"})});
854 Cmd->SectionCommands.push_back(ISD);
859 Cmd->MemoryRegionName = next();
863 Cmd->LMARegionName = next();
866 if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
867 error("section can't have both LMA and a load region");
869 Cmd->Phdrs = readOutputSectionPhdrs();
872 Cmd->Filler = parseFill(next());
873 else if (peek().startswith("="))
874 Cmd->Filler = parseFill(next().drop_front());
876 // Consume optional comma following output section command.
879 if (Script->ReferencedSymbols.size() > SymbolsReferenced)
880 Cmd->ExpressionsUseSymbols = true;
884 // Parses a given string as a octal/decimal/hexadecimal number and
885 // returns it as a big-endian number. Used for `=<fillexp>`.
886 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
888 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
889 // size, while ld.gold always handles it as a 32-bit big-endian number.
890 // We are compatible with ld.gold because it's easier to implement.
891 std::array<uint8_t, 4> ScriptParser::parseFill(StringRef Tok) {
893 if (!to_integer(Tok, V))
894 setError("invalid filler expression: " + Tok);
896 std::array<uint8_t, 4> Buf;
897 write32be(Buf.data(), V);
901 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
903 SymbolAssignment *Cmd = readSymbolAssignment(next());
904 Cmd->Provide = Provide;
905 Cmd->Hidden = Hidden;
910 SymbolAssignment *ScriptParser::readAssignment(StringRef Tok) {
911 // Assert expression returns Dot, so this is equal to ".=."
913 return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
916 SymbolAssignment *Cmd = nullptr;
917 if (peek() == "=" || peek() == "+=")
918 Cmd = readSymbolAssignment(Tok);
919 else if (Tok == "PROVIDE")
920 Cmd = readProvideHidden(true, false);
921 else if (Tok == "HIDDEN")
922 Cmd = readProvideHidden(false, true);
923 else if (Tok == "PROVIDE_HIDDEN")
924 Cmd = readProvideHidden(true, true);
929 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
935 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
936 StringRef Op = next();
937 assert(Op == "=" || Op == "+=");
940 std::string Loc = getCurrentLocation();
941 E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
943 return make<SymbolAssignment>(Name, E, getCurrentLocation());
946 // This is an operator-precedence parser to parse a linker
947 // script expression.
948 Expr ScriptParser::readExpr() {
949 // Our lexer is context-aware. Set the in-expression bit so that
950 // they apply different tokenization rules.
953 Expr E = readExpr1(readPrimary(), 0);
958 Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
960 return [=] { return add(L(), R()); };
962 return [=] { return sub(L(), R()); };
964 return [=] { return L().getValue() * R().getValue(); };
966 std::string Loc = getCurrentLocation();
967 return [=]() -> uint64_t {
968 if (uint64_t RV = R().getValue())
969 return L().getValue() / RV;
970 error(Loc + ": division by zero");
975 std::string Loc = getCurrentLocation();
976 return [=]() -> uint64_t {
977 if (uint64_t RV = R().getValue())
978 return L().getValue() % RV;
979 error(Loc + ": modulo by zero");
984 return [=] { return L().getValue() << R().getValue(); };
986 return [=] { return L().getValue() >> R().getValue(); };
988 return [=] { return L().getValue() < R().getValue(); };
990 return [=] { return L().getValue() > R().getValue(); };
992 return [=] { return L().getValue() >= R().getValue(); };
994 return [=] { return L().getValue() <= R().getValue(); };
996 return [=] { return L().getValue() == R().getValue(); };
998 return [=] { return L().getValue() != R().getValue(); };
1000 return [=] { return L().getValue() || R().getValue(); };
1002 return [=] { return L().getValue() && R().getValue(); };
1004 return [=] { return bitAnd(L(), R()); };
1006 return [=] { return bitOr(L(), R()); };
1007 llvm_unreachable("invalid operator");
1010 // This is a part of the operator-precedence parser. This function
1011 // assumes that the remaining token stream starts with an operator.
1012 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1013 while (!atEOF() && !errorCount()) {
1014 // Read an operator and an expression.
1016 return readTernary(Lhs);
1017 StringRef Op1 = peek();
1018 if (precedence(Op1) < MinPrec)
1021 Expr Rhs = readPrimary();
1023 // Evaluate the remaining part of the expression first if the
1024 // next operator has greater precedence than the previous one.
1025 // For example, if we have read "+" and "3", and if the next
1026 // operator is "*", then we'll evaluate 3 * ... part first.
1028 StringRef Op2 = peek();
1029 if (precedence(Op2) <= precedence(Op1))
1031 Rhs = readExpr1(Rhs, precedence(Op2));
1034 Lhs = combine(Op1, Lhs, Rhs);
1039 Expr ScriptParser::getPageSize() {
1040 std::string Location = getCurrentLocation();
1041 return [=]() -> uint64_t {
1043 return Target->PageSize;
1044 error(Location + ": unable to calculate page size");
1045 return 4096; // Return a dummy value.
1049 Expr ScriptParser::readConstant() {
1050 StringRef S = readParenLiteral();
1051 if (S == "COMMONPAGESIZE")
1052 return getPageSize();
1053 if (S == "MAXPAGESIZE")
1054 return [] { return Config->MaxPageSize; };
1055 setError("unknown constant: " + S);
1056 return [] { return 0; };
1059 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1060 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1061 // have "K" (Ki) or "M" (Mi) suffixes.
1062 static Optional<uint64_t> parseInt(StringRef Tok) {
1065 if (Tok.startswith_lower("0x")) {
1066 if (!to_integer(Tok.substr(2), Val, 16))
1070 if (Tok.endswith_lower("H")) {
1071 if (!to_integer(Tok.drop_back(), Val, 16))
1077 if (Tok.endswith_lower("K")) {
1078 if (!to_integer(Tok.drop_back(), Val, 10))
1082 if (Tok.endswith_lower("M")) {
1083 if (!to_integer(Tok.drop_back(), Val, 10))
1085 return Val * 1024 * 1024;
1087 if (!to_integer(Tok, Val, 10))
1092 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
1093 int Size = StringSwitch<int>(Tok)
1102 size_t OldPos = Pos;
1103 Expr E = readParenExpr();
1104 std::string CommandString =
1106 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
1107 return make<ByteCommand>(E, Size, CommandString);
1110 StringRef ScriptParser::readParenLiteral() {
1114 StringRef Tok = next();
1120 static void checkIfExists(OutputSection *Cmd, StringRef Location) {
1121 if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
1122 error(Location + ": undefined section " + Cmd->Name);
1125 Expr ScriptParser::readPrimary() {
1127 return readParenExpr();
1130 Expr E = readPrimary();
1131 return [=] { return ~E().getValue(); };
1134 Expr E = readPrimary();
1135 return [=] { return !E().getValue(); };
1138 Expr E = readPrimary();
1139 return [=] { return -E().getValue(); };
1142 StringRef Tok = next();
1143 std::string Location = getCurrentLocation();
1145 // Built-in functions are parsed here.
1146 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1147 if (Tok == "ABSOLUTE") {
1148 Expr Inner = readParenExpr();
1150 ExprValue I = Inner();
1151 I.ForceAbsolute = true;
1155 if (Tok == "ADDR") {
1156 StringRef Name = readParenLiteral();
1157 OutputSection *Sec = Script->getOrCreateOutputSection(Name);
1158 return [=]() -> ExprValue {
1159 checkIfExists(Sec, Location);
1160 return {Sec, false, 0, Location};
1163 if (Tok == "ALIGN") {
1165 Expr E = readExpr();
1167 E = checkAlignment(E, Location);
1168 return [=] { return alignTo(Script->getDot(), E().getValue()); };
1171 Expr E2 = checkAlignment(readExpr(), Location);
1175 V.Alignment = E2().getValue();
1179 if (Tok == "ALIGNOF") {
1180 StringRef Name = readParenLiteral();
1181 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1183 checkIfExists(Cmd, Location);
1184 return Cmd->Alignment;
1187 if (Tok == "ASSERT")
1188 return readAssert();
1189 if (Tok == "CONSTANT")
1190 return readConstant();
1191 if (Tok == "DATA_SEGMENT_ALIGN") {
1193 Expr E = readExpr();
1198 return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1201 if (Tok == "DATA_SEGMENT_END") {
1205 return [] { return Script->getDot(); };
1207 if (Tok == "DATA_SEGMENT_RELRO_END") {
1208 // GNU linkers implements more complicated logic to handle
1209 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1210 // just align to the next page boundary for simplicity.
1216 Expr E = getPageSize();
1217 return [=] { return alignTo(Script->getDot(), E().getValue()); };
1219 if (Tok == "DEFINED") {
1220 StringRef Name = readParenLiteral();
1221 return [=] { return Symtab->find(Name) ? 1 : 0; };
1223 if (Tok == "LENGTH") {
1224 StringRef Name = readParenLiteral();
1225 if (Script->MemoryRegions.count(Name) == 0) {
1226 setError("memory region not defined: " + Name);
1227 return [] { return 0; };
1229 return [=] { return Script->MemoryRegions[Name]->Length; };
1231 if (Tok == "LOADADDR") {
1232 StringRef Name = readParenLiteral();
1233 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1235 checkIfExists(Cmd, Location);
1236 return Cmd->getLMA();
1239 if (Tok == "MAX" || Tok == "MIN") {
1241 Expr A = readExpr();
1243 Expr B = readExpr();
1246 return [=] { return std::min(A().getValue(), B().getValue()); };
1247 return [=] { return std::max(A().getValue(), B().getValue()); };
1249 if (Tok == "ORIGIN") {
1250 StringRef Name = readParenLiteral();
1251 if (Script->MemoryRegions.count(Name) == 0) {
1252 setError("memory region not defined: " + Name);
1253 return [] { return 0; };
1255 return [=] { return Script->MemoryRegions[Name]->Origin; };
1257 if (Tok == "SEGMENT_START") {
1261 Expr E = readExpr();
1263 return [=] { return E(); };
1265 if (Tok == "SIZEOF") {
1266 StringRef Name = readParenLiteral();
1267 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1268 // Linker script does not create an output section if its content is empty.
1269 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1271 return [=] { return Cmd->Size; };
1273 if (Tok == "SIZEOF_HEADERS")
1274 return [=] { return elf::getHeaderSize(); };
1278 return [=] { return Script->getSymbolValue(Tok, Location); };
1280 // Tok is a literal number.
1281 if (Optional<uint64_t> Val = parseInt(Tok))
1282 return [=] { return *Val; };
1284 // Tok is a symbol name.
1285 if (!isValidCIdentifier(Tok))
1286 setError("malformed number: " + Tok);
1287 Script->ReferencedSymbols.push_back(Tok);
1288 return [=] { return Script->getSymbolValue(Tok, Location); };
1291 Expr ScriptParser::readTernary(Expr Cond) {
1292 Expr L = readExpr();
1294 Expr R = readExpr();
1295 return [=] { return Cond().getValue() ? L() : R(); };
1298 Expr ScriptParser::readParenExpr() {
1300 Expr E = readExpr();
1305 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1306 std::vector<StringRef> Phdrs;
1307 while (!errorCount() && peek().startswith(":")) {
1308 StringRef Tok = next();
1309 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1314 // Read a program header type name. The next token must be a
1315 // name of a program header type or a constant (e.g. "0x3").
1316 unsigned ScriptParser::readPhdrType() {
1317 StringRef Tok = next();
1318 if (Optional<uint64_t> Val = parseInt(Tok))
1321 unsigned Ret = StringSwitch<unsigned>(Tok)
1322 .Case("PT_NULL", PT_NULL)
1323 .Case("PT_LOAD", PT_LOAD)
1324 .Case("PT_DYNAMIC", PT_DYNAMIC)
1325 .Case("PT_INTERP", PT_INTERP)
1326 .Case("PT_NOTE", PT_NOTE)
1327 .Case("PT_SHLIB", PT_SHLIB)
1328 .Case("PT_PHDR", PT_PHDR)
1329 .Case("PT_TLS", PT_TLS)
1330 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1331 .Case("PT_GNU_STACK", PT_GNU_STACK)
1332 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1333 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1334 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1335 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1338 if (Ret == (unsigned)-1) {
1339 setError("invalid program header type: " + Tok);
1345 // Reads an anonymous version declaration.
1346 void ScriptParser::readAnonymousDeclaration() {
1347 std::vector<SymbolVersion> Locals;
1348 std::vector<SymbolVersion> Globals;
1349 std::tie(Locals, Globals) = readSymbols();
1351 for (SymbolVersion V : Locals) {
1353 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1355 Config->VersionScriptLocals.push_back(V);
1358 for (SymbolVersion V : Globals)
1359 Config->VersionScriptGlobals.push_back(V);
1364 // Reads a non-anonymous version definition,
1365 // e.g. "VerStr { global: foo; bar; local: *; };".
1366 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1367 // Read a symbol list.
1368 std::vector<SymbolVersion> Locals;
1369 std::vector<SymbolVersion> Globals;
1370 std::tie(Locals, Globals) = readSymbols();
1372 for (SymbolVersion V : Locals) {
1374 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1376 Config->VersionScriptLocals.push_back(V);
1379 // Create a new version definition and add that to the global symbols.
1380 VersionDefinition Ver;
1382 Ver.Globals = Globals;
1384 // User-defined version number starts from 2 because 0 and 1 are
1385 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1386 Ver.Id = Config->VersionDefinitions.size() + 2;
1387 Config->VersionDefinitions.push_back(Ver);
1389 // Each version may have a parent version. For example, "Ver2"
1390 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1391 // as a parent. This version hierarchy is, probably against your
1392 // instinct, purely for hint; the runtime doesn't care about it
1393 // at all. In LLD, we simply ignore it.
1399 static bool hasWildcard(StringRef S) {
1400 return S.find_first_of("?*[") != StringRef::npos;
1403 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1404 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1405 ScriptParser::readSymbols() {
1406 std::vector<SymbolVersion> Locals;
1407 std::vector<SymbolVersion> Globals;
1408 std::vector<SymbolVersion> *V = &Globals;
1410 while (!errorCount()) {
1413 if (consumeLabel("local")) {
1417 if (consumeLabel("global")) {
1422 if (consume("extern")) {
1423 std::vector<SymbolVersion> Ext = readVersionExtern();
1424 V->insert(V->end(), Ext.begin(), Ext.end());
1426 StringRef Tok = next();
1427 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1431 return {Locals, Globals};
1434 // Reads an "extern C++" directive, e.g.,
1435 // "extern "C++" { ns::*; "f(int, double)"; };"
1437 // The last semicolon is optional. E.g. this is OK:
1438 // "extern "C++" { ns::*; "f(int, double)" };"
1439 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1440 StringRef Tok = next();
1441 bool IsCXX = Tok == "\"C++\"";
1442 if (!IsCXX && Tok != "\"C\"")
1443 setError("Unknown language");
1446 std::vector<SymbolVersion> Ret;
1447 while (!errorCount() && peek() != "}") {
1448 StringRef Tok = next();
1449 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1450 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1460 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1462 if (!consume(S1) && !consume(S2) && !consume(S3)) {
1463 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1467 return readExpr()().getValue();
1470 // Parse the MEMORY command as specified in:
1471 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1473 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1474 void ScriptParser::readMemory() {
1476 while (!errorCount() && !consume("}")) {
1477 StringRef Tok = next();
1478 if (Tok == "INCLUDE") {
1484 uint32_t NegFlags = 0;
1486 std::tie(Flags, NegFlags) = readMemoryAttributes();
1491 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1493 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1495 // Add the memory region to the region map.
1496 MemoryRegion *MR = make<MemoryRegion>(Tok, Origin, Length, Flags, NegFlags);
1497 if (!Script->MemoryRegions.insert({Tok, MR}).second)
1498 setError("region '" + Tok + "' already defined");
1502 // This function parses the attributes used to match against section
1503 // flags when placing output sections in a memory region. These flags
1504 // are only used when an explicit memory region name is not used.
1505 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1507 uint32_t NegFlags = 0;
1508 bool Invert = false;
1510 for (char C : next().lower()) {
1517 Flag = SHF_EXECINSTR;
1521 setError("invalid memory region attribute");
1528 return {Flags, NegFlags};
1531 void elf::readLinkerScript(MemoryBufferRef MB) {
1532 ScriptParser(MB).readLinkerScript();
1535 void elf::readVersionScript(MemoryBufferRef MB) {
1536 ScriptParser(MB).readVersionScript();
1539 void elf::readDynamicList(MemoryBufferRef MB) {
1540 ScriptParser(MB).readDynamicList();
1543 void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
1544 ScriptParser(MB).readDefsym(Name);