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);
68 void readOutputArch();
69 void readOutputFormat();
71 void readRegionAlias();
75 void readVersionScriptCommand();
77 SymbolAssignment *readAssignment(StringRef Name);
78 ByteCommand *readByteCommand(StringRef Tok);
80 uint32_t parseFill(StringRef Tok);
81 void readSectionAddressType(OutputSection *Cmd);
82 OutputSection *readOutputSectionDescription(StringRef OutSec);
83 std::vector<StringRef> readOutputSectionPhdrs();
84 InputSectionDescription *readInputSectionDescription(StringRef Tok);
85 StringMatcher readFilePatterns();
86 std::vector<SectionPattern> readInputSectionsList();
87 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
88 unsigned readPhdrType();
89 SortSectionPolicy readSortKind();
90 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
91 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
93 AssertCommand *readAssert();
94 Expr readAssertExpr();
98 uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
99 std::pair<uint32_t, uint32_t> readMemoryAttributes();
102 Expr readExpr1(Expr Lhs, int MinPrec);
103 StringRef readParenLiteral();
105 Expr readTernary(Expr Cond);
106 Expr readParenExpr();
108 // For parsing version script.
109 std::vector<SymbolVersion> readVersionExtern();
110 void readAnonymousDeclaration();
111 void readVersionDeclaration(StringRef VerStr);
113 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
116 // True if a script being read is in a subdirectory specified by -sysroot.
119 // A set to detect an INCLUDE() cycle.
124 static StringRef unquote(StringRef S) {
125 if (S.startswith("\""))
126 return S.substr(1, S.size() - 2);
130 static bool isUnderSysroot(StringRef Path) {
131 if (Config->Sysroot == "")
133 for (; !Path.empty(); Path = sys::path::parent_path(Path))
134 if (sys::fs::equivalent(Config->Sysroot, Path))
139 // Some operations only support one non absolute value. Move the
140 // absolute one to the right hand side for convenience.
141 static void moveAbsRight(ExprValue &A, ExprValue &B) {
142 if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
145 error(A.Loc + ": at least one side of the expression must be absolute");
148 static ExprValue add(ExprValue A, ExprValue B) {
150 return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
153 static ExprValue sub(ExprValue A, ExprValue B) {
154 // The distance between two symbols in sections is absolute.
155 if (!A.isAbsolute() && !B.isAbsolute())
156 return A.getValue() - B.getValue();
157 return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
160 static ExprValue mul(ExprValue A, ExprValue B) {
161 return A.getValue() * B.getValue();
164 static ExprValue div(ExprValue A, ExprValue B) {
165 if (uint64_t BV = B.getValue())
166 return A.getValue() / BV;
167 error("division by zero");
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 bitOr(ExprValue A, ExprValue B) {
179 return {A.Sec, A.ForceAbsolute,
180 (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
183 void ScriptParser::readDynamicList() {
184 Config->HasDynamicList = true;
186 std::vector<SymbolVersion> Locals;
187 std::vector<SymbolVersion> Globals;
188 std::tie(Locals, Globals) = readSymbols();
192 setError("EOF expected, but got " + next());
195 if (!Locals.empty()) {
196 setError("\"local:\" scope not supported in --dynamic-list");
200 for (SymbolVersion V : Globals)
201 Config->DynamicList.push_back(V);
204 void ScriptParser::readVersionScript() {
205 readVersionScriptCommand();
207 setError("EOF expected, but got " + next());
210 void ScriptParser::readVersionScriptCommand() {
212 readAnonymousDeclaration();
216 while (!atEOF() && !errorCount() && peek() != "}") {
217 StringRef VerStr = next();
219 setError("anonymous version definition is used in "
220 "combination with other version definitions");
224 readVersionDeclaration(VerStr);
228 void ScriptParser::readVersion() {
230 readVersionScriptCommand();
234 void ScriptParser::readLinkerScript() {
236 StringRef Tok = next();
240 if (Tok == "ASSERT") {
241 Script->SectionCommands.push_back(readAssert());
242 } else if (Tok == "ENTRY") {
244 } else if (Tok == "EXTERN") {
246 } else if (Tok == "GROUP" || Tok == "INPUT") {
248 } else if (Tok == "INCLUDE") {
250 } else if (Tok == "MEMORY") {
252 } else if (Tok == "OUTPUT") {
254 } else if (Tok == "OUTPUT_ARCH") {
256 } else if (Tok == "OUTPUT_FORMAT") {
258 } else if (Tok == "PHDRS") {
260 } else if (Tok == "REGION_ALIAS") {
262 } else if (Tok == "SEARCH_DIR") {
264 } else if (Tok == "SECTIONS") {
266 } else if (Tok == "VERSION") {
268 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
269 Script->SectionCommands.push_back(Cmd);
271 setError("unknown directive: " + Tok);
276 void ScriptParser::readDefsym(StringRef Name) {
279 setError("EOF expected, but got " + next());
280 SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
281 Script->SectionCommands.push_back(Cmd);
284 void ScriptParser::addFile(StringRef S) {
285 if (IsUnderSysroot && S.startswith("/")) {
286 SmallString<128> PathData;
287 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
288 if (sys::fs::exists(Path)) {
289 Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
294 if (S.startswith("/")) {
295 Driver->addFile(S, /*WithLOption=*/false);
296 } else if (S.startswith("=")) {
297 if (Config->Sysroot.empty())
298 Driver->addFile(S.substr(1), /*WithLOption=*/false);
300 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
301 /*WithLOption=*/false);
302 } else if (S.startswith("-l")) {
303 Driver->addLibrary(S.substr(2));
304 } else if (sys::fs::exists(S)) {
305 Driver->addFile(S, /*WithLOption=*/false);
307 if (Optional<std::string> Path = findFromSearchPaths(S))
308 Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
310 setError("unable to find " + S);
314 void ScriptParser::readAsNeeded() {
316 bool Orig = Config->AsNeeded;
317 Config->AsNeeded = true;
318 while (!errorCount() && !consume(")"))
319 addFile(unquote(next()));
320 Config->AsNeeded = Orig;
323 void ScriptParser::readEntry() {
324 // -e <symbol> takes predecence over ENTRY(<symbol>).
326 StringRef Tok = next();
327 if (Config->Entry.empty())
332 void ScriptParser::readExtern() {
334 while (!errorCount() && !consume(")"))
335 Config->Undefined.push_back(next());
338 void ScriptParser::readGroup() {
340 while (!errorCount() && !consume(")")) {
341 if (consume("AS_NEEDED"))
344 addFile(unquote(next()));
348 void ScriptParser::readInclude() {
349 StringRef Tok = unquote(next());
351 if (!Seen.insert(Tok).second) {
352 setError("there is a cycle in linker script INCLUDEs");
356 if (Optional<std::string> Path = searchLinkerScript(Tok)) {
357 if (Optional<MemoryBufferRef> MB = readFile(*Path))
361 setError("cannot find linker script " + Tok);
364 void ScriptParser::readOutput() {
365 // -o <file> takes predecence over OUTPUT(<file>).
367 StringRef Tok = next();
368 if (Config->OutputFile.empty())
369 Config->OutputFile = unquote(Tok);
373 void ScriptParser::readOutputArch() {
374 // OUTPUT_ARCH is ignored for now.
376 while (!errorCount() && !consume(")"))
380 void ScriptParser::readOutputFormat() {
381 // Error checking only for now.
393 void ScriptParser::readPhdrs() {
396 while (!errorCount() && !consume("}")) {
399 Cmd.Type = readPhdrType();
401 while (!errorCount() && !consume(";")) {
402 if (consume("FILEHDR"))
403 Cmd.HasFilehdr = true;
404 else if (consume("PHDRS"))
406 else if (consume("AT"))
407 Cmd.LMAExpr = readParenExpr();
408 else if (consume("FLAGS"))
409 Cmd.Flags = readParenExpr()().getValue();
411 setError("unexpected header attribute: " + next());
414 Script->PhdrsCommands.push_back(Cmd);
418 void ScriptParser::readRegionAlias() {
420 StringRef Alias = unquote(next());
422 StringRef Name = next();
425 if (Script->MemoryRegions.count(Alias))
426 setError("redefinition of memory region '" + Alias + "'");
427 if (!Script->MemoryRegions.count(Name))
428 setError("memory region '" + Name + "' is not defined");
429 Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
432 void ScriptParser::readSearchDir() {
434 StringRef Tok = next();
435 if (!Config->Nostdlib)
436 Config->SearchPaths.push_back(unquote(Tok));
440 void ScriptParser::readSections() {
441 Script->HasSectionsCommand = true;
443 // -no-rosegment is used to avoid placing read only non-executable sections in
444 // their own segment. We do the same if SECTIONS command is present in linker
445 // script. See comment for computeFlags().
446 Config->SingleRoRx = true;
449 while (!errorCount() && !consume("}")) {
450 StringRef Tok = next();
451 BaseCommand *Cmd = readProvideOrAssignment(Tok);
456 Cmd = readOutputSectionDescription(Tok);
458 Script->SectionCommands.push_back(Cmd);
462 static int precedence(StringRef Op) {
463 return StringSwitch<int>(Op)
466 .Cases("<<", ">>", 3)
467 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
472 StringMatcher ScriptParser::readFilePatterns() {
473 std::vector<StringRef> V;
474 while (!errorCount() && !consume(")"))
476 return StringMatcher(V);
479 SortSectionPolicy ScriptParser::readSortKind() {
480 if (consume("SORT") || consume("SORT_BY_NAME"))
481 return SortSectionPolicy::Name;
482 if (consume("SORT_BY_ALIGNMENT"))
483 return SortSectionPolicy::Alignment;
484 if (consume("SORT_BY_INIT_PRIORITY"))
485 return SortSectionPolicy::Priority;
486 if (consume("SORT_NONE"))
487 return SortSectionPolicy::None;
488 return SortSectionPolicy::Default;
491 // Reads SECTIONS command contents in the following form:
493 // <contents> ::= <elem>*
494 // <elem> ::= <exclude>? <glob-pattern>
495 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
499 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
501 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
502 // The semantics of that is section .foo in any file, section .bar in
503 // any file but a.o, and section .baz in any file but b.o.
504 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
505 std::vector<SectionPattern> Ret;
506 while (!errorCount() && peek() != ")") {
507 StringMatcher ExcludeFilePat;
508 if (consume("EXCLUDE_FILE")) {
510 ExcludeFilePat = readFilePatterns();
513 std::vector<StringRef> V;
514 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
518 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
520 setError("section pattern is expected");
525 // Reads contents of "SECTIONS" directive. That directive contains a
526 // list of glob patterns for input sections. The grammar is as follows.
528 // <patterns> ::= <section-list>
529 // | <sort> "(" <section-list> ")"
530 // | <sort> "(" <sort> "(" <section-list> ")" ")"
532 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
533 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
535 // <section-list> is parsed by readInputSectionsList().
536 InputSectionDescription *
537 ScriptParser::readInputSectionRules(StringRef FilePattern) {
538 auto *Cmd = make<InputSectionDescription>(FilePattern);
541 while (!errorCount() && !consume(")")) {
542 SortSectionPolicy Outer = readSortKind();
543 SortSectionPolicy Inner = SortSectionPolicy::Default;
544 std::vector<SectionPattern> V;
545 if (Outer != SortSectionPolicy::Default) {
547 Inner = readSortKind();
548 if (Inner != SortSectionPolicy::Default) {
550 V = readInputSectionsList();
553 V = readInputSectionsList();
557 V = readInputSectionsList();
560 for (SectionPattern &Pat : V) {
561 Pat.SortInner = Inner;
562 Pat.SortOuter = Outer;
565 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
570 InputSectionDescription *
571 ScriptParser::readInputSectionDescription(StringRef Tok) {
572 // Input section wildcard can be surrounded by KEEP.
573 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
576 StringRef FilePattern = next();
577 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
579 Script->KeptSections.push_back(Cmd);
582 return readInputSectionRules(Tok);
585 void ScriptParser::readSort() {
587 expect("CONSTRUCTORS");
591 AssertCommand *ScriptParser::readAssert() {
592 return make<AssertCommand>(readAssertExpr());
595 Expr ScriptParser::readAssertExpr() {
599 StringRef Msg = unquote(next());
605 return Script->getDot();
609 // Reads a FILL(expr) command. We handle the FILL command as an
610 // alias for =fillexp section attribute, which is different from
611 // what GNU linkers do.
612 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
613 uint32_t ScriptParser::readFill() {
615 uint32_t V = parseFill(next());
620 // Reads an expression and/or the special directive "(NOLOAD)" for an
621 // output section definition.
623 // An output section name can be followed by an address expression
624 // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be
625 // interpreted as either the beginning of some expression or "(NOLOAD)".
627 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
628 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
629 void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
631 if (consume("NOLOAD")) {
636 Cmd->AddrExpr = readExpr();
639 Cmd->AddrExpr = readExpr();
649 static Expr checkAlignment(Expr E, std::string &Loc) {
651 uint64_t Alignment = std::max((uint64_t)1, E().getValue());
652 if (!isPowerOf2_64(Alignment)) {
653 error(Loc + ": alignment must be power of 2");
654 return (uint64_t)1; // Return a dummy value.
660 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
662 Script->createOutputSection(OutSec, getCurrentLocation());
665 readSectionAddressType(Cmd);
668 std::string Location = getCurrentLocation();
670 Cmd->LMAExpr = readParenExpr();
671 if (consume("ALIGN"))
672 Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
673 if (consume("SUBALIGN"))
674 Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
676 // Parse constraints.
677 if (consume("ONLY_IF_RO"))
678 Cmd->Constraint = ConstraintKind::ReadOnly;
679 if (consume("ONLY_IF_RW"))
680 Cmd->Constraint = ConstraintKind::ReadWrite;
683 while (!errorCount() && !consume("}")) {
684 StringRef Tok = next();
686 // Empty commands are allowed. Do nothing here.
687 } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
688 Cmd->SectionCommands.push_back(Assign);
689 } else if (ByteCommand *Data = readByteCommand(Tok)) {
690 Cmd->SectionCommands.push_back(Data);
691 } else if (Tok == "ASSERT") {
692 Cmd->SectionCommands.push_back(readAssert());
694 } else if (Tok == "CONSTRUCTORS") {
695 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
696 // by name. This is for very old file formats such as ECOFF/XCOFF.
697 // For ELF, we should ignore.
698 } else if (Tok == "FILL") {
699 Cmd->Filler = readFill();
700 } else if (Tok == "SORT") {
702 } else if (peek() == "(") {
703 Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
705 setError("unknown command " + Tok);
710 Cmd->MemoryRegionName = next();
714 Cmd->LMARegionName = next();
717 if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
718 error("section can't have both LMA and a load region");
720 Cmd->Phdrs = readOutputSectionPhdrs();
723 Cmd->Filler = parseFill(next());
724 else if (peek().startswith("="))
725 Cmd->Filler = parseFill(next().drop_front());
727 // Consume optional comma following output section command.
733 // Parses a given string as a octal/decimal/hexadecimal number and
734 // returns it as a big-endian number. Used for `=<fillexp>`.
735 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
737 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
738 // size, while ld.gold always handles it as a 32-bit big-endian number.
739 // We are compatible with ld.gold because it's easier to implement.
740 uint32_t ScriptParser::parseFill(StringRef Tok) {
742 if (!to_integer(Tok, V))
743 setError("invalid filler expression: " + Tok);
750 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
752 SymbolAssignment *Cmd = readAssignment(next());
753 Cmd->Provide = Provide;
754 Cmd->Hidden = Hidden;
760 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
761 SymbolAssignment *Cmd = nullptr;
762 if (peek() == "=" || peek() == "+=") {
763 Cmd = readAssignment(Tok);
765 } else if (Tok == "PROVIDE") {
766 Cmd = readProvideHidden(true, false);
767 } else if (Tok == "HIDDEN") {
768 Cmd = readProvideHidden(false, true);
769 } else if (Tok == "PROVIDE_HIDDEN") {
770 Cmd = readProvideHidden(true, true);
775 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
776 StringRef Op = next();
777 assert(Op == "=" || Op == "+=");
780 std::string Loc = getCurrentLocation();
781 E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
783 return make<SymbolAssignment>(Name, E, getCurrentLocation());
786 // This is an operator-precedence parser to parse a linker
787 // script expression.
788 Expr ScriptParser::readExpr() {
789 // Our lexer is context-aware. Set the in-expression bit so that
790 // they apply different tokenization rules.
793 Expr E = readExpr1(readPrimary(), 0);
798 static Expr combine(StringRef Op, Expr L, Expr R) {
800 return [=] { return add(L(), R()); };
802 return [=] { return sub(L(), R()); };
804 return [=] { return mul(L(), R()); };
806 return [=] { return div(L(), R()); };
808 return [=] { return L().getValue() << R().getValue(); };
810 return [=] { return L().getValue() >> R().getValue(); };
812 return [=] { return L().getValue() < R().getValue(); };
814 return [=] { return L().getValue() > R().getValue(); };
816 return [=] { return L().getValue() >= R().getValue(); };
818 return [=] { return L().getValue() <= R().getValue(); };
820 return [=] { return L().getValue() == R().getValue(); };
822 return [=] { return L().getValue() != R().getValue(); };
824 return [=] { return bitAnd(L(), R()); };
826 return [=] { return bitOr(L(), R()); };
827 llvm_unreachable("invalid operator");
830 // This is a part of the operator-precedence parser. This function
831 // assumes that the remaining token stream starts with an operator.
832 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
833 while (!atEOF() && !errorCount()) {
834 // Read an operator and an expression.
836 return readTernary(Lhs);
837 StringRef Op1 = peek();
838 if (precedence(Op1) < MinPrec)
841 Expr Rhs = readPrimary();
843 // Evaluate the remaining part of the expression first if the
844 // next operator has greater precedence than the previous one.
845 // For example, if we have read "+" and "3", and if the next
846 // operator is "*", then we'll evaluate 3 * ... part first.
848 StringRef Op2 = peek();
849 if (precedence(Op2) <= precedence(Op1))
851 Rhs = readExpr1(Rhs, precedence(Op2));
854 Lhs = combine(Op1, Lhs, Rhs);
859 Expr ScriptParser::getPageSize() {
860 std::string Location = getCurrentLocation();
861 return [=]() -> uint64_t {
863 return Target->PageSize;
864 error(Location + ": unable to calculate page size");
865 return 4096; // Return a dummy value.
869 Expr ScriptParser::readConstant() {
870 StringRef S = readParenLiteral();
871 if (S == "COMMONPAGESIZE")
872 return getPageSize();
873 if (S == "MAXPAGESIZE")
874 return [] { return Config->MaxPageSize; };
875 setError("unknown constant: " + S);
879 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
880 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
881 // have "K" (Ki) or "M" (Mi) suffixes.
882 static Optional<uint64_t> parseInt(StringRef Tok) {
884 if (Tok.startswith("-")) {
885 if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
892 if (Tok.startswith_lower("0x")) {
893 if (!to_integer(Tok.substr(2), Val, 16))
897 if (Tok.endswith_lower("H")) {
898 if (!to_integer(Tok.drop_back(), Val, 16))
904 if (Tok.endswith_lower("K")) {
905 if (!to_integer(Tok.drop_back(), Val, 10))
909 if (Tok.endswith_lower("M")) {
910 if (!to_integer(Tok.drop_back(), Val, 10))
912 return Val * 1024 * 1024;
914 if (!to_integer(Tok, Val, 10))
919 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
920 int Size = StringSwitch<int>(Tok)
928 return make<ByteCommand>(readParenExpr(), Size);
931 StringRef ScriptParser::readParenLiteral() {
935 StringRef Tok = next();
941 static void checkIfExists(OutputSection *Cmd, StringRef Location) {
942 if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
943 error(Location + ": undefined section " + Cmd->Name);
946 Expr ScriptParser::readPrimary() {
948 return readParenExpr();
951 Expr E = readPrimary();
952 return [=] { return ~E().getValue(); };
955 Expr E = readPrimary();
956 return [=] { return !E().getValue(); };
959 Expr E = readPrimary();
960 return [=] { return -E().getValue(); };
963 StringRef Tok = next();
964 std::string Location = getCurrentLocation();
966 // Built-in functions are parsed here.
967 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
968 if (Tok == "ABSOLUTE") {
969 Expr Inner = readParenExpr();
971 ExprValue I = Inner();
972 I.ForceAbsolute = true;
977 StringRef Name = readParenLiteral();
978 OutputSection *Sec = Script->getOrCreateOutputSection(Name);
979 return [=]() -> ExprValue {
980 checkIfExists(Sec, Location);
981 return {Sec, false, 0, Location};
984 if (Tok == "ALIGN") {
988 E = checkAlignment(E, Location);
989 return [=] { return alignTo(Script->getDot(), E().getValue()); };
992 Expr E2 = checkAlignment(readExpr(), Location);
996 V.Alignment = E2().getValue();
1000 if (Tok == "ALIGNOF") {
1001 StringRef Name = readParenLiteral();
1002 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1004 checkIfExists(Cmd, Location);
1005 return Cmd->Alignment;
1008 if (Tok == "ASSERT")
1009 return readAssertExpr();
1010 if (Tok == "CONSTANT")
1011 return readConstant();
1012 if (Tok == "DATA_SEGMENT_ALIGN") {
1014 Expr E = readExpr();
1019 return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1022 if (Tok == "DATA_SEGMENT_END") {
1026 return [] { return Script->getDot(); };
1028 if (Tok == "DATA_SEGMENT_RELRO_END") {
1029 // GNU linkers implements more complicated logic to handle
1030 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1031 // just align to the next page boundary for simplicity.
1037 Expr E = getPageSize();
1038 return [=] { return alignTo(Script->getDot(), E().getValue()); };
1040 if (Tok == "DEFINED") {
1041 StringRef Name = readParenLiteral();
1042 return [=] { return Symtab->find(Name) ? 1 : 0; };
1044 if (Tok == "LENGTH") {
1045 StringRef Name = readParenLiteral();
1046 if (Script->MemoryRegions.count(Name) == 0)
1047 setError("memory region not defined: " + Name);
1048 return [=] { return Script->MemoryRegions[Name]->Length; };
1050 if (Tok == "LOADADDR") {
1051 StringRef Name = readParenLiteral();
1052 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1054 checkIfExists(Cmd, Location);
1055 return Cmd->getLMA();
1058 if (Tok == "ORIGIN") {
1059 StringRef Name = readParenLiteral();
1060 if (Script->MemoryRegions.count(Name) == 0)
1061 setError("memory region not defined: " + Name);
1062 return [=] { return Script->MemoryRegions[Name]->Origin; };
1064 if (Tok == "SEGMENT_START") {
1068 Expr E = readExpr();
1070 return [=] { return E(); };
1072 if (Tok == "SIZEOF") {
1073 StringRef Name = readParenLiteral();
1074 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1075 // Linker script does not create an output section if its content is empty.
1076 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1078 return [=] { return Cmd->Size; };
1080 if (Tok == "SIZEOF_HEADERS")
1081 return [=] { return elf::getHeaderSize(); };
1085 return [=] { return Script->getSymbolValue(Tok, Location); };
1087 // Tok is a literal number.
1088 if (Optional<uint64_t> Val = parseInt(Tok))
1089 return [=] { return *Val; };
1091 // Tok is a symbol name.
1092 if (!isValidCIdentifier(Tok))
1093 setError("malformed number: " + Tok);
1094 Script->ReferencedSymbols.push_back(Tok);
1095 return [=] { return Script->getSymbolValue(Tok, Location); };
1098 Expr ScriptParser::readTernary(Expr Cond) {
1099 Expr L = readExpr();
1101 Expr R = readExpr();
1102 return [=] { return Cond().getValue() ? L() : R(); };
1105 Expr ScriptParser::readParenExpr() {
1107 Expr E = readExpr();
1112 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1113 std::vector<StringRef> Phdrs;
1114 while (!errorCount() && peek().startswith(":")) {
1115 StringRef Tok = next();
1116 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1121 // Read a program header type name. The next token must be a
1122 // name of a program header type or a constant (e.g. "0x3").
1123 unsigned ScriptParser::readPhdrType() {
1124 StringRef Tok = next();
1125 if (Optional<uint64_t> Val = parseInt(Tok))
1128 unsigned Ret = StringSwitch<unsigned>(Tok)
1129 .Case("PT_NULL", PT_NULL)
1130 .Case("PT_LOAD", PT_LOAD)
1131 .Case("PT_DYNAMIC", PT_DYNAMIC)
1132 .Case("PT_INTERP", PT_INTERP)
1133 .Case("PT_NOTE", PT_NOTE)
1134 .Case("PT_SHLIB", PT_SHLIB)
1135 .Case("PT_PHDR", PT_PHDR)
1136 .Case("PT_TLS", PT_TLS)
1137 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1138 .Case("PT_GNU_STACK", PT_GNU_STACK)
1139 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1140 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1141 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1142 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1145 if (Ret == (unsigned)-1) {
1146 setError("invalid program header type: " + Tok);
1152 // Reads an anonymous version declaration.
1153 void ScriptParser::readAnonymousDeclaration() {
1154 std::vector<SymbolVersion> Locals;
1155 std::vector<SymbolVersion> Globals;
1156 std::tie(Locals, Globals) = readSymbols();
1158 for (SymbolVersion V : Locals) {
1160 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1162 Config->VersionScriptLocals.push_back(V);
1165 for (SymbolVersion V : Globals)
1166 Config->VersionScriptGlobals.push_back(V);
1171 // Reads a non-anonymous version definition,
1172 // e.g. "VerStr { global: foo; bar; local: *; };".
1173 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1174 // Read a symbol list.
1175 std::vector<SymbolVersion> Locals;
1176 std::vector<SymbolVersion> Globals;
1177 std::tie(Locals, Globals) = readSymbols();
1179 for (SymbolVersion V : Locals) {
1181 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1183 Config->VersionScriptLocals.push_back(V);
1186 // Create a new version definition and add that to the global symbols.
1187 VersionDefinition Ver;
1189 Ver.Globals = Globals;
1191 // User-defined version number starts from 2 because 0 and 1 are
1192 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1193 Ver.Id = Config->VersionDefinitions.size() + 2;
1194 Config->VersionDefinitions.push_back(Ver);
1196 // Each version may have a parent version. For example, "Ver2"
1197 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1198 // as a parent. This version hierarchy is, probably against your
1199 // instinct, purely for hint; the runtime doesn't care about it
1200 // at all. In LLD, we simply ignore it.
1206 static bool hasWildcard(StringRef S) {
1207 return S.find_first_of("?*[") != StringRef::npos;
1210 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1211 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1212 ScriptParser::readSymbols() {
1213 std::vector<SymbolVersion> Locals;
1214 std::vector<SymbolVersion> Globals;
1215 std::vector<SymbolVersion> *V = &Globals;
1217 while (!errorCount()) {
1220 if (consumeLabel("local")) {
1224 if (consumeLabel("global")) {
1229 if (consume("extern")) {
1230 std::vector<SymbolVersion> Ext = readVersionExtern();
1231 V->insert(V->end(), Ext.begin(), Ext.end());
1233 StringRef Tok = next();
1234 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1238 return {Locals, Globals};
1241 // Reads an "extern C++" directive, e.g.,
1242 // "extern "C++" { ns::*; "f(int, double)"; };"
1243 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1244 StringRef Tok = next();
1245 bool IsCXX = Tok == "\"C++\"";
1246 if (!IsCXX && Tok != "\"C\"")
1247 setError("Unknown language");
1250 std::vector<SymbolVersion> Ret;
1251 while (!errorCount() && peek() != "}") {
1252 StringRef Tok = next();
1253 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1254 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1262 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1264 if (!consume(S1) && !consume(S2) && !consume(S3)) {
1265 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1269 return readExpr()().getValue();
1272 // Parse the MEMORY command as specified in:
1273 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1275 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1276 void ScriptParser::readMemory() {
1278 while (!errorCount() && !consume("}")) {
1279 StringRef Name = next();
1282 uint32_t NegFlags = 0;
1284 std::tie(Flags, NegFlags) = readMemoryAttributes();
1289 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1291 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1293 // Add the memory region to the region map.
1294 if (Script->MemoryRegions.count(Name))
1295 setError("region '" + Name + "' already defined");
1297 make<MemoryRegion>(Name, Origin, Length, Flags, NegFlags);
1298 Script->MemoryRegions[Name] = MR;
1302 // This function parses the attributes used to match against section
1303 // flags when placing output sections in a memory region. These flags
1304 // are only used when an explicit memory region name is not used.
1305 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1307 uint32_t NegFlags = 0;
1308 bool Invert = false;
1310 for (char C : next().lower()) {
1317 Flag = SHF_EXECINSTR;
1321 setError("invalid memory region attribute");
1328 return {Flags, NegFlags};
1331 void elf::readLinkerScript(MemoryBufferRef MB) {
1332 ScriptParser(MB).readLinkerScript();
1335 void elf::readVersionScript(MemoryBufferRef MB) {
1336 ScriptParser(MB).readVersionScript();
1339 void elf::readDynamicList(MemoryBufferRef MB) {
1340 ScriptParser(MB).readDynamicList();
1343 void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
1344 ScriptParser(MB).readDefsym(Name);