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("elf64-powerpc", {ELF64BEKind, EM_PPC64})
396 .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
397 .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
398 .Case("elf32-tradbigmips", {ELF32BEKind, EM_MIPS})
399 .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
400 .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
401 .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
402 .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
403 .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
404 .Default({ELFNoneKind, EM_NONE});
407 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(bfdname, big, little).
408 // Currently we ignore big and little parameters.
409 void ScriptParser::readOutputFormat() {
412 StringRef Name = unquote(next());
414 if (S.consume_back("-freebsd"))
415 Config->OSABI = ELFOSABI_FREEBSD;
417 std::tie(Config->EKind, Config->EMachine) = parseBfdName(S);
418 if (Config->EMachine == EM_NONE)
419 setError("unknown output format name: " + Name);
420 if (S == "elf32-ntradlittlemips" || S == "elf32-ntradbigmips")
421 Config->MipsN32Abi = true;
432 void ScriptParser::readPhdrs() {
435 while (!errorCount() && !consume("}")) {
438 Cmd.Type = readPhdrType();
440 while (!errorCount() && !consume(";")) {
441 if (consume("FILEHDR"))
442 Cmd.HasFilehdr = true;
443 else if (consume("PHDRS"))
445 else if (consume("AT"))
446 Cmd.LMAExpr = readParenExpr();
447 else if (consume("FLAGS"))
448 Cmd.Flags = readParenExpr()().getValue();
450 setError("unexpected header attribute: " + next());
453 Script->PhdrsCommands.push_back(Cmd);
457 void ScriptParser::readRegionAlias() {
459 StringRef Alias = unquote(next());
461 StringRef Name = next();
464 if (Script->MemoryRegions.count(Alias))
465 setError("redefinition of memory region '" + Alias + "'");
466 if (!Script->MemoryRegions.count(Name))
467 setError("memory region '" + Name + "' is not defined");
468 Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
471 void ScriptParser::readSearchDir() {
473 StringRef Tok = next();
474 if (!Config->Nostdlib)
475 Config->SearchPaths.push_back(unquote(Tok));
479 // This reads an overlay description. Overlays are used to describe output
480 // sections that use the same virtual memory range and normally would trigger
481 // linker's sections sanity check failures.
482 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
483 std::vector<BaseCommand *> ScriptParser::readOverlay() {
484 // VA and LMA expressions are optional, though for simplicity of
485 // implementation we assume they are not. That is what OVERLAY was designed
486 // for first of all: to allow sections with overlapping VAs at different LMAs.
487 Expr AddrExpr = readExpr();
490 Expr LMAExpr = readParenExpr();
493 std::vector<BaseCommand *> V;
494 OutputSection *Prev = nullptr;
495 while (!errorCount() && !consume("}")) {
496 // VA is the same for all sections. The LMAs are consecutive in memory
497 // starting from the base load address specified.
498 OutputSection *OS = readOverlaySectionDescription();
499 OS->AddrExpr = AddrExpr;
501 OS->LMAExpr = [=] { return Prev->getLMA() + Prev->Size; };
503 OS->LMAExpr = LMAExpr;
508 // According to the specification, at the end of the overlay, the location
509 // counter should be equal to the overlay base address plus size of the
510 // largest section seen in the overlay.
511 // Here we want to create the Dot assignment command to achieve that.
514 for (BaseCommand *Cmd : V)
515 Max = std::max(Max, cast<OutputSection>(Cmd)->Size);
516 return AddrExpr().getValue() + Max;
518 V.push_back(make<SymbolAssignment>(".", MoveDot, getCurrentLocation()));
522 void ScriptParser::readSections() {
523 Script->HasSectionsCommand = true;
525 // -no-rosegment is used to avoid placing read only non-executable sections in
526 // their own segment. We do the same if SECTIONS command is present in linker
527 // script. See comment for computeFlags().
528 Config->SingleRoRx = true;
531 std::vector<BaseCommand *> V;
532 while (!errorCount() && !consume("}")) {
533 StringRef Tok = next();
534 if (Tok == "OVERLAY") {
535 for (BaseCommand *Cmd : readOverlay())
538 } else if (Tok == "INCLUDE") {
543 if (BaseCommand *Cmd = readAssignment(Tok))
546 V.push_back(readOutputSectionDescription(Tok));
549 if (!atEOF() && consume("INSERT")) {
550 std::vector<BaseCommand *> *Dest = nullptr;
551 if (consume("AFTER"))
552 Dest = &Script->InsertAfterCommands[next()];
553 else if (consume("BEFORE"))
554 Dest = &Script->InsertBeforeCommands[next()];
556 setError("expected AFTER/BEFORE, but got '" + next() + "'");
558 Dest->insert(Dest->end(), V.begin(), V.end());
562 Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(),
566 void ScriptParser::readTarget() {
567 // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
568 // we accept only a limited set of BFD names (i.e. "elf" or "binary")
569 // for --format. We recognize only /^elf/ and "binary" in the linker
572 StringRef Tok = next();
575 if (Tok.startswith("elf"))
576 Config->FormatBinary = false;
577 else if (Tok == "binary")
578 Config->FormatBinary = true;
580 setError("unknown target: " + Tok);
583 static int precedence(StringRef Op) {
584 return StringSwitch<int>(Op)
585 .Cases("*", "/", "%", 8)
587 .Cases("<<", ">>", 6)
588 .Cases("<", "<=", ">", ">=", "==", "!=", 5)
596 StringMatcher ScriptParser::readFilePatterns() {
597 std::vector<StringRef> V;
598 while (!errorCount() && !consume(")"))
600 return StringMatcher(V);
603 SortSectionPolicy ScriptParser::readSortKind() {
604 if (consume("SORT") || consume("SORT_BY_NAME"))
605 return SortSectionPolicy::Name;
606 if (consume("SORT_BY_ALIGNMENT"))
607 return SortSectionPolicy::Alignment;
608 if (consume("SORT_BY_INIT_PRIORITY"))
609 return SortSectionPolicy::Priority;
610 if (consume("SORT_NONE"))
611 return SortSectionPolicy::None;
612 return SortSectionPolicy::Default;
615 // Reads SECTIONS command contents in the following form:
617 // <contents> ::= <elem>*
618 // <elem> ::= <exclude>? <glob-pattern>
619 // <exclude> ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
623 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
625 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
626 // The semantics of that is section .foo in any file, section .bar in
627 // any file but a.o, and section .baz in any file but b.o.
628 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
629 std::vector<SectionPattern> Ret;
630 while (!errorCount() && peek() != ")") {
631 StringMatcher ExcludeFilePat;
632 if (consume("EXCLUDE_FILE")) {
634 ExcludeFilePat = readFilePatterns();
637 std::vector<StringRef> V;
638 while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
642 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
644 setError("section pattern is expected");
649 // Reads contents of "SECTIONS" directive. That directive contains a
650 // list of glob patterns for input sections. The grammar is as follows.
652 // <patterns> ::= <section-list>
653 // | <sort> "(" <section-list> ")"
654 // | <sort> "(" <sort> "(" <section-list> ")" ")"
656 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
657 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
659 // <section-list> is parsed by readInputSectionsList().
660 InputSectionDescription *
661 ScriptParser::readInputSectionRules(StringRef FilePattern) {
662 auto *Cmd = make<InputSectionDescription>(FilePattern);
665 while (!errorCount() && !consume(")")) {
666 SortSectionPolicy Outer = readSortKind();
667 SortSectionPolicy Inner = SortSectionPolicy::Default;
668 std::vector<SectionPattern> V;
669 if (Outer != SortSectionPolicy::Default) {
671 Inner = readSortKind();
672 if (Inner != SortSectionPolicy::Default) {
674 V = readInputSectionsList();
677 V = readInputSectionsList();
681 V = readInputSectionsList();
684 for (SectionPattern &Pat : V) {
685 Pat.SortInner = Inner;
686 Pat.SortOuter = Outer;
689 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
694 InputSectionDescription *
695 ScriptParser::readInputSectionDescription(StringRef Tok) {
696 // Input section wildcard can be surrounded by KEEP.
697 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
700 StringRef FilePattern = next();
701 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
703 Script->KeptSections.push_back(Cmd);
706 return readInputSectionRules(Tok);
709 void ScriptParser::readSort() {
711 expect("CONSTRUCTORS");
715 Expr ScriptParser::readAssert() {
719 StringRef Msg = unquote(next());
725 return Script->getDot();
729 // Reads a FILL(expr) command. We handle the FILL command as an
730 // alias for =fillexp section attribute, which is different from
731 // what GNU linkers do.
732 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
733 std::array<uint8_t, 4> ScriptParser::readFill() {
735 std::array<uint8_t, 4> V = parseFill(next());
740 // Tries to read the special directive for an output section definition which
741 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
742 // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
743 bool ScriptParser::readSectionDirective(OutputSection *Cmd, StringRef Tok1, StringRef Tok2) {
746 if (Tok2 != "NOLOAD" && Tok2 != "COPY" && Tok2 != "INFO" && Tok2 != "OVERLAY")
750 if (consume("NOLOAD")) {
753 skip(); // This is "COPY", "INFO" or "OVERLAY".
754 Cmd->NonAlloc = true;
760 // Reads an expression and/or the special directive for an output
761 // section definition. Directive is one of following: "(NOLOAD)",
762 // "(COPY)", "(INFO)" or "(OVERLAY)".
764 // An output section name can be followed by an address expression
765 // and/or directive. This grammar is not LL(1) because "(" can be
766 // interpreted as either the beginning of some expression or beginning
769 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
770 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
771 void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
772 if (readSectionDirective(Cmd, peek(), peek2()))
775 Cmd->AddrExpr = readExpr();
776 if (peek() == "(" && !readSectionDirective(Cmd, "(", peek2()))
777 setError("unknown section directive: " + peek2());
780 static Expr checkAlignment(Expr E, std::string &Loc) {
782 uint64_t Alignment = std::max((uint64_t)1, E().getValue());
783 if (!isPowerOf2_64(Alignment)) {
784 error(Loc + ": alignment must be power of 2");
785 return (uint64_t)1; // Return a dummy value.
791 OutputSection *ScriptParser::readOverlaySectionDescription() {
793 Script->createOutputSection(next(), getCurrentLocation());
794 Cmd->InOverlay = true;
796 while (!errorCount() && !consume("}"))
797 Cmd->SectionCommands.push_back(readInputSectionRules(next()));
798 Cmd->Phdrs = readOutputSectionPhdrs();
802 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
804 Script->createOutputSection(OutSec, getCurrentLocation());
806 size_t SymbolsReferenced = Script->ReferencedSymbols.size();
809 readSectionAddressType(Cmd);
812 std::string Location = getCurrentLocation();
814 Cmd->LMAExpr = readParenExpr();
815 if (consume("ALIGN"))
816 Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
817 if (consume("SUBALIGN"))
818 Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
820 // Parse constraints.
821 if (consume("ONLY_IF_RO"))
822 Cmd->Constraint = ConstraintKind::ReadOnly;
823 if (consume("ONLY_IF_RW"))
824 Cmd->Constraint = ConstraintKind::ReadWrite;
827 while (!errorCount() && !consume("}")) {
828 StringRef Tok = next();
830 // Empty commands are allowed. Do nothing here.
831 } else if (SymbolAssignment *Assign = readAssignment(Tok)) {
832 Cmd->SectionCommands.push_back(Assign);
833 } else if (ByteCommand *Data = readByteCommand(Tok)) {
834 Cmd->SectionCommands.push_back(Data);
835 } else if (Tok == "CONSTRUCTORS") {
836 // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
837 // by name. This is for very old file formats such as ECOFF/XCOFF.
838 // For ELF, we should ignore.
839 } else if (Tok == "FILL") {
840 Cmd->Filler = readFill();
841 } else if (Tok == "SORT") {
843 } else if (Tok == "INCLUDE") {
845 } else if (peek() == "(") {
846 Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
848 // We have a file name and no input sections description. It is not a
849 // commonly used syntax, but still acceptable. In that case, all sections
850 // from the file will be included.
851 auto *ISD = make<InputSectionDescription>(Tok);
852 ISD->SectionPatterns.push_back({{}, StringMatcher({"*"})});
853 Cmd->SectionCommands.push_back(ISD);
858 Cmd->MemoryRegionName = next();
862 Cmd->LMARegionName = next();
865 if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
866 error("section can't have both LMA and a load region");
868 Cmd->Phdrs = readOutputSectionPhdrs();
871 Cmd->Filler = parseFill(next());
872 else if (peek().startswith("="))
873 Cmd->Filler = parseFill(next().drop_front());
875 // Consume optional comma following output section command.
878 if (Script->ReferencedSymbols.size() > SymbolsReferenced)
879 Cmd->ExpressionsUseSymbols = true;
883 // Parses a given string as a octal/decimal/hexadecimal number and
884 // returns it as a big-endian number. Used for `=<fillexp>`.
885 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
887 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
888 // size, while ld.gold always handles it as a 32-bit big-endian number.
889 // We are compatible with ld.gold because it's easier to implement.
890 std::array<uint8_t, 4> ScriptParser::parseFill(StringRef Tok) {
892 if (!to_integer(Tok, V))
893 setError("invalid filler expression: " + Tok);
895 std::array<uint8_t, 4> Buf;
896 write32be(Buf.data(), V);
900 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
902 SymbolAssignment *Cmd = readSymbolAssignment(next());
903 Cmd->Provide = Provide;
904 Cmd->Hidden = Hidden;
909 SymbolAssignment *ScriptParser::readAssignment(StringRef Tok) {
910 // Assert expression returns Dot, so this is equal to ".=."
912 return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
915 SymbolAssignment *Cmd = nullptr;
916 if (peek() == "=" || peek() == "+=")
917 Cmd = readSymbolAssignment(Tok);
918 else if (Tok == "PROVIDE")
919 Cmd = readProvideHidden(true, false);
920 else if (Tok == "HIDDEN")
921 Cmd = readProvideHidden(false, true);
922 else if (Tok == "PROVIDE_HIDDEN")
923 Cmd = readProvideHidden(true, true);
928 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
934 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
935 StringRef Op = next();
936 assert(Op == "=" || Op == "+=");
939 std::string Loc = getCurrentLocation();
940 E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
942 return make<SymbolAssignment>(Name, E, getCurrentLocation());
945 // This is an operator-precedence parser to parse a linker
946 // script expression.
947 Expr ScriptParser::readExpr() {
948 // Our lexer is context-aware. Set the in-expression bit so that
949 // they apply different tokenization rules.
952 Expr E = readExpr1(readPrimary(), 0);
957 Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
959 return [=] { return add(L(), R()); };
961 return [=] { return sub(L(), R()); };
963 return [=] { return L().getValue() * R().getValue(); };
965 std::string Loc = getCurrentLocation();
966 return [=]() -> uint64_t {
967 if (uint64_t RV = R().getValue())
968 return L().getValue() / RV;
969 error(Loc + ": division by zero");
974 std::string Loc = getCurrentLocation();
975 return [=]() -> uint64_t {
976 if (uint64_t RV = R().getValue())
977 return L().getValue() % RV;
978 error(Loc + ": modulo by zero");
983 return [=] { return L().getValue() << R().getValue(); };
985 return [=] { return L().getValue() >> R().getValue(); };
987 return [=] { return L().getValue() < R().getValue(); };
989 return [=] { return L().getValue() > R().getValue(); };
991 return [=] { return L().getValue() >= R().getValue(); };
993 return [=] { return L().getValue() <= R().getValue(); };
995 return [=] { return L().getValue() == R().getValue(); };
997 return [=] { return L().getValue() != R().getValue(); };
999 return [=] { return L().getValue() || R().getValue(); };
1001 return [=] { return L().getValue() && R().getValue(); };
1003 return [=] { return bitAnd(L(), R()); };
1005 return [=] { return bitOr(L(), R()); };
1006 llvm_unreachable("invalid operator");
1009 // This is a part of the operator-precedence parser. This function
1010 // assumes that the remaining token stream starts with an operator.
1011 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1012 while (!atEOF() && !errorCount()) {
1013 // Read an operator and an expression.
1015 return readTernary(Lhs);
1016 StringRef Op1 = peek();
1017 if (precedence(Op1) < MinPrec)
1020 Expr Rhs = readPrimary();
1022 // Evaluate the remaining part of the expression first if the
1023 // next operator has greater precedence than the previous one.
1024 // For example, if we have read "+" and "3", and if the next
1025 // operator is "*", then we'll evaluate 3 * ... part first.
1027 StringRef Op2 = peek();
1028 if (precedence(Op2) <= precedence(Op1))
1030 Rhs = readExpr1(Rhs, precedence(Op2));
1033 Lhs = combine(Op1, Lhs, Rhs);
1038 Expr ScriptParser::getPageSize() {
1039 std::string Location = getCurrentLocation();
1040 return [=]() -> uint64_t {
1042 return Target->PageSize;
1043 error(Location + ": unable to calculate page size");
1044 return 4096; // Return a dummy value.
1048 Expr ScriptParser::readConstant() {
1049 StringRef S = readParenLiteral();
1050 if (S == "COMMONPAGESIZE")
1051 return getPageSize();
1052 if (S == "MAXPAGESIZE")
1053 return [] { return Config->MaxPageSize; };
1054 setError("unknown constant: " + S);
1055 return [] { return 0; };
1058 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1059 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1060 // have "K" (Ki) or "M" (Mi) suffixes.
1061 static Optional<uint64_t> parseInt(StringRef Tok) {
1064 if (Tok.startswith_lower("0x")) {
1065 if (!to_integer(Tok.substr(2), Val, 16))
1069 if (Tok.endswith_lower("H")) {
1070 if (!to_integer(Tok.drop_back(), Val, 16))
1076 if (Tok.endswith_lower("K")) {
1077 if (!to_integer(Tok.drop_back(), Val, 10))
1081 if (Tok.endswith_lower("M")) {
1082 if (!to_integer(Tok.drop_back(), Val, 10))
1084 return Val * 1024 * 1024;
1086 if (!to_integer(Tok, Val, 10))
1091 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
1092 int Size = StringSwitch<int>(Tok)
1101 size_t OldPos = Pos;
1102 Expr E = readParenExpr();
1103 std::string CommandString =
1105 llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
1106 return make<ByteCommand>(E, Size, CommandString);
1109 StringRef ScriptParser::readParenLiteral() {
1113 StringRef Tok = next();
1119 static void checkIfExists(OutputSection *Cmd, StringRef Location) {
1120 if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
1121 error(Location + ": undefined section " + Cmd->Name);
1124 Expr ScriptParser::readPrimary() {
1126 return readParenExpr();
1129 Expr E = readPrimary();
1130 return [=] { return ~E().getValue(); };
1133 Expr E = readPrimary();
1134 return [=] { return !E().getValue(); };
1137 Expr E = readPrimary();
1138 return [=] { return -E().getValue(); };
1141 StringRef Tok = next();
1142 std::string Location = getCurrentLocation();
1144 // Built-in functions are parsed here.
1145 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1146 if (Tok == "ABSOLUTE") {
1147 Expr Inner = readParenExpr();
1149 ExprValue I = Inner();
1150 I.ForceAbsolute = true;
1154 if (Tok == "ADDR") {
1155 StringRef Name = readParenLiteral();
1156 OutputSection *Sec = Script->getOrCreateOutputSection(Name);
1157 return [=]() -> ExprValue {
1158 checkIfExists(Sec, Location);
1159 return {Sec, false, 0, Location};
1162 if (Tok == "ALIGN") {
1164 Expr E = readExpr();
1166 E = checkAlignment(E, Location);
1167 return [=] { return alignTo(Script->getDot(), E().getValue()); };
1170 Expr E2 = checkAlignment(readExpr(), Location);
1174 V.Alignment = E2().getValue();
1178 if (Tok == "ALIGNOF") {
1179 StringRef Name = readParenLiteral();
1180 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1182 checkIfExists(Cmd, Location);
1183 return Cmd->Alignment;
1186 if (Tok == "ASSERT")
1187 return readAssert();
1188 if (Tok == "CONSTANT")
1189 return readConstant();
1190 if (Tok == "DATA_SEGMENT_ALIGN") {
1192 Expr E = readExpr();
1197 return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1200 if (Tok == "DATA_SEGMENT_END") {
1204 return [] { return Script->getDot(); };
1206 if (Tok == "DATA_SEGMENT_RELRO_END") {
1207 // GNU linkers implements more complicated logic to handle
1208 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1209 // just align to the next page boundary for simplicity.
1215 Expr E = getPageSize();
1216 return [=] { return alignTo(Script->getDot(), E().getValue()); };
1218 if (Tok == "DEFINED") {
1219 StringRef Name = readParenLiteral();
1220 return [=] { return Symtab->find(Name) ? 1 : 0; };
1222 if (Tok == "LENGTH") {
1223 StringRef Name = readParenLiteral();
1224 if (Script->MemoryRegions.count(Name) == 0) {
1225 setError("memory region not defined: " + Name);
1226 return [] { return 0; };
1228 return [=] { return Script->MemoryRegions[Name]->Length; };
1230 if (Tok == "LOADADDR") {
1231 StringRef Name = readParenLiteral();
1232 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1234 checkIfExists(Cmd, Location);
1235 return Cmd->getLMA();
1238 if (Tok == "MAX" || Tok == "MIN") {
1240 Expr A = readExpr();
1242 Expr B = readExpr();
1245 return [=] { return std::min(A().getValue(), B().getValue()); };
1246 return [=] { return std::max(A().getValue(), B().getValue()); };
1248 if (Tok == "ORIGIN") {
1249 StringRef Name = readParenLiteral();
1250 if (Script->MemoryRegions.count(Name) == 0) {
1251 setError("memory region not defined: " + Name);
1252 return [] { return 0; };
1254 return [=] { return Script->MemoryRegions[Name]->Origin; };
1256 if (Tok == "SEGMENT_START") {
1260 Expr E = readExpr();
1262 return [=] { return E(); };
1264 if (Tok == "SIZEOF") {
1265 StringRef Name = readParenLiteral();
1266 OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1267 // Linker script does not create an output section if its content is empty.
1268 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1270 return [=] { return Cmd->Size; };
1272 if (Tok == "SIZEOF_HEADERS")
1273 return [=] { return elf::getHeaderSize(); };
1277 return [=] { return Script->getSymbolValue(Tok, Location); };
1279 // Tok is a literal number.
1280 if (Optional<uint64_t> Val = parseInt(Tok))
1281 return [=] { return *Val; };
1283 // Tok is a symbol name.
1284 if (!isValidCIdentifier(Tok))
1285 setError("malformed number: " + Tok);
1286 Script->ReferencedSymbols.push_back(Tok);
1287 return [=] { return Script->getSymbolValue(Tok, Location); };
1290 Expr ScriptParser::readTernary(Expr Cond) {
1291 Expr L = readExpr();
1293 Expr R = readExpr();
1294 return [=] { return Cond().getValue() ? L() : R(); };
1297 Expr ScriptParser::readParenExpr() {
1299 Expr E = readExpr();
1304 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1305 std::vector<StringRef> Phdrs;
1306 while (!errorCount() && peek().startswith(":")) {
1307 StringRef Tok = next();
1308 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1313 // Read a program header type name. The next token must be a
1314 // name of a program header type or a constant (e.g. "0x3").
1315 unsigned ScriptParser::readPhdrType() {
1316 StringRef Tok = next();
1317 if (Optional<uint64_t> Val = parseInt(Tok))
1320 unsigned Ret = StringSwitch<unsigned>(Tok)
1321 .Case("PT_NULL", PT_NULL)
1322 .Case("PT_LOAD", PT_LOAD)
1323 .Case("PT_DYNAMIC", PT_DYNAMIC)
1324 .Case("PT_INTERP", PT_INTERP)
1325 .Case("PT_NOTE", PT_NOTE)
1326 .Case("PT_SHLIB", PT_SHLIB)
1327 .Case("PT_PHDR", PT_PHDR)
1328 .Case("PT_TLS", PT_TLS)
1329 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1330 .Case("PT_GNU_STACK", PT_GNU_STACK)
1331 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1332 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1333 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1334 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1337 if (Ret == (unsigned)-1) {
1338 setError("invalid program header type: " + Tok);
1344 // Reads an anonymous version declaration.
1345 void ScriptParser::readAnonymousDeclaration() {
1346 std::vector<SymbolVersion> Locals;
1347 std::vector<SymbolVersion> Globals;
1348 std::tie(Locals, Globals) = readSymbols();
1350 for (SymbolVersion V : Locals) {
1352 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1354 Config->VersionScriptLocals.push_back(V);
1357 for (SymbolVersion V : Globals)
1358 Config->VersionScriptGlobals.push_back(V);
1363 // Reads a non-anonymous version definition,
1364 // e.g. "VerStr { global: foo; bar; local: *; };".
1365 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1366 // Read a symbol list.
1367 std::vector<SymbolVersion> Locals;
1368 std::vector<SymbolVersion> Globals;
1369 std::tie(Locals, Globals) = readSymbols();
1371 for (SymbolVersion V : Locals) {
1373 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1375 Config->VersionScriptLocals.push_back(V);
1378 // Create a new version definition and add that to the global symbols.
1379 VersionDefinition Ver;
1381 Ver.Globals = Globals;
1383 // User-defined version number starts from 2 because 0 and 1 are
1384 // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1385 Ver.Id = Config->VersionDefinitions.size() + 2;
1386 Config->VersionDefinitions.push_back(Ver);
1388 // Each version may have a parent version. For example, "Ver2"
1389 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1390 // as a parent. This version hierarchy is, probably against your
1391 // instinct, purely for hint; the runtime doesn't care about it
1392 // at all. In LLD, we simply ignore it.
1398 static bool hasWildcard(StringRef S) {
1399 return S.find_first_of("?*[") != StringRef::npos;
1402 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1403 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1404 ScriptParser::readSymbols() {
1405 std::vector<SymbolVersion> Locals;
1406 std::vector<SymbolVersion> Globals;
1407 std::vector<SymbolVersion> *V = &Globals;
1409 while (!errorCount()) {
1412 if (consumeLabel("local")) {
1416 if (consumeLabel("global")) {
1421 if (consume("extern")) {
1422 std::vector<SymbolVersion> Ext = readVersionExtern();
1423 V->insert(V->end(), Ext.begin(), Ext.end());
1425 StringRef Tok = next();
1426 V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1430 return {Locals, Globals};
1433 // Reads an "extern C++" directive, e.g.,
1434 // "extern "C++" { ns::*; "f(int, double)"; };"
1436 // The last semicolon is optional. E.g. this is OK:
1437 // "extern "C++" { ns::*; "f(int, double)" };"
1438 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1439 StringRef Tok = next();
1440 bool IsCXX = Tok == "\"C++\"";
1441 if (!IsCXX && Tok != "\"C\"")
1442 setError("Unknown language");
1445 std::vector<SymbolVersion> Ret;
1446 while (!errorCount() && peek() != "}") {
1447 StringRef Tok = next();
1448 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1449 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1459 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1461 if (!consume(S1) && !consume(S2) && !consume(S3)) {
1462 setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1466 return readExpr()().getValue();
1469 // Parse the MEMORY command as specified in:
1470 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1472 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1473 void ScriptParser::readMemory() {
1475 while (!errorCount() && !consume("}")) {
1476 StringRef Tok = next();
1477 if (Tok == "INCLUDE") {
1483 uint32_t NegFlags = 0;
1485 std::tie(Flags, NegFlags) = readMemoryAttributes();
1490 uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1492 uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1494 // Add the memory region to the region map.
1495 MemoryRegion *MR = make<MemoryRegion>(Tok, Origin, Length, Flags, NegFlags);
1496 if (!Script->MemoryRegions.insert({Tok, MR}).second)
1497 setError("region '" + Tok + "' already defined");
1501 // This function parses the attributes used to match against section
1502 // flags when placing output sections in a memory region. These flags
1503 // are only used when an explicit memory region name is not used.
1504 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1506 uint32_t NegFlags = 0;
1507 bool Invert = false;
1509 for (char C : next().lower()) {
1516 Flag = SHF_EXECINSTR;
1520 setError("invalid memory region attribute");
1527 return {Flags, NegFlags};
1530 void elf::readLinkerScript(MemoryBufferRef MB) {
1531 ScriptParser(MB).readLinkerScript();
1534 void elf::readVersionScript(MemoryBufferRef MB) {
1535 ScriptParser(MB).readVersionScript();
1538 void elf::readDynamicList(MemoryBufferRef MB) {
1539 ScriptParser(MB).readDynamicList();
1542 void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
1543 ScriptParser(MB).readDefsym(Name);