1 //===- LinkerScript.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 the parser/evaluator of the linker script.
12 //===----------------------------------------------------------------------===//
14 #include "LinkerScript.h"
17 #include "InputSection.h"
19 #include "OutputSections.h"
20 #include "ScriptParser.h"
22 #include "SymbolTable.h"
24 #include "SyntheticSections.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
50 using namespace llvm::ELF;
51 using namespace llvm::object;
52 using namespace llvm::support::endian;
54 using namespace lld::elf;
56 LinkerScriptBase *elf::ScriptBase;
57 ScriptConfiguration *elf::ScriptConfig;
59 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
60 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
61 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
62 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
64 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
66 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, /*IsLocal=*/false,
67 Visibility, STT_NOTYPE, 0, 0, nullptr,
72 template <class ELFT> static SymbolBody *addSynthetic(SymbolAssignment *Cmd) {
73 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
74 const OutputSectionBase *Sec =
75 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
76 Symbol *Sym = Symtab<ELFT>::X->addUndefined(
77 Cmd->Name, /*IsLocal=*/false, STB_GLOBAL, Visibility,
79 /*CanOmitFromDynSym*/ false, /*File*/ nullptr);
81 replaceBody<DefinedSynthetic>(Sym, Cmd->Name, 0, Sec);
85 static bool isUnderSysroot(StringRef Path) {
86 if (Config->Sysroot == "")
88 for (; !Path.empty(); Path = sys::path::parent_path(Path))
89 if (sys::fs::equivalent(Config->Sysroot, Path))
94 template <class ELFT> static void assignSymbol(SymbolAssignment *Cmd) {
95 // If there are sections, then let the value be assigned later in
97 if (ScriptConfig->HasSections)
100 uint64_t Value = Cmd->Expression(0);
101 if (Cmd->Expression.IsAbsolute()) {
102 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Value;
104 const OutputSectionBase *Sec = Cmd->Expression.Section();
106 cast<DefinedSynthetic>(Cmd->Sym)->Value = Value - Sec->Addr;
110 template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
111 if (Cmd->Name == ".")
114 // If a symbol was in PROVIDE(), we need to define it only when
115 // it is a referenced undefined symbol.
116 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
117 if (Cmd->Provide && (!B || B->isDefined()))
120 // Otherwise, create a new symbol if one does not exist or an
121 // undefined one does exist.
122 if (Cmd->Expression.IsAbsolute())
123 Cmd->Sym = addRegular<ELFT>(Cmd);
125 Cmd->Sym = addSynthetic<ELFT>(Cmd);
126 assignSymbol<ELFT>(Cmd);
129 bool SymbolAssignment::classof(const BaseCommand *C) {
130 return C->Kind == AssignmentKind;
133 bool OutputSectionCommand::classof(const BaseCommand *C) {
134 return C->Kind == OutputSectionKind;
137 bool InputSectionDescription::classof(const BaseCommand *C) {
138 return C->Kind == InputSectionKind;
141 bool AssertCommand::classof(const BaseCommand *C) {
142 return C->Kind == AssertKind;
145 bool BytesDataCommand::classof(const BaseCommand *C) {
146 return C->Kind == BytesDataKind;
149 template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
150 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
152 template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
154 return sys::path::filename(S->getFile()->getName());
158 template <class ELFT>
159 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
160 for (InputSectionDescription *ID : Opt.KeptSections)
161 if (ID->FilePat.match(basename(S)))
162 for (SectionPattern &P : ID->SectionPatterns)
163 if (P.SectionPat.match(S->Name))
168 static bool comparePriority(InputSectionData *A, InputSectionData *B) {
169 return getPriority(A->Name) < getPriority(B->Name);
172 static bool compareName(InputSectionData *A, InputSectionData *B) {
173 return A->Name < B->Name;
176 static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
177 // ">" is not a mistake. Larger alignments are placed before smaller
178 // alignments in order to reduce the amount of padding necessary.
179 // This is compatible with GNU.
180 return A->Alignment > B->Alignment;
183 static std::function<bool(InputSectionData *, InputSectionData *)>
184 getComparator(SortSectionPolicy K) {
186 case SortSectionPolicy::Alignment:
187 return compareAlignment;
188 case SortSectionPolicy::Name:
190 case SortSectionPolicy::Priority:
191 return comparePriority;
193 llvm_unreachable("unknown sort policy");
197 template <class ELFT>
198 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
199 ConstraintKind Kind) {
200 if (Kind == ConstraintKind::NoConstraint)
202 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
203 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
204 return Sec->Flags & SHF_WRITE;
206 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
207 (!IsRW && Kind == ConstraintKind::ReadOnly);
210 static void sortSections(InputSectionData **Begin, InputSectionData **End,
211 SortSectionPolicy K) {
212 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
213 std::stable_sort(Begin, End, getComparator(K));
216 // Compute and remember which sections the InputSectionDescription matches.
217 template <class ELFT>
218 void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
219 // Collects all sections that satisfy constraints of I
220 // and attach them to I.
221 for (SectionPattern &Pat : I->SectionPatterns) {
222 size_t SizeBefore = I->Sections.size();
224 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
225 if (!S->Live || S->Assigned)
228 StringRef Filename = basename(S);
229 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
231 if (!Pat.SectionPat.match(S->Name))
233 I->Sections.push_back(S);
237 // Sort sections as instructed by SORT-family commands and --sort-section
238 // option. Because SORT-family commands can be nested at most two depth
239 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
240 // line option is respected even if a SORT command is given, the exact
241 // behavior we have here is a bit complicated. Here are the rules.
243 // 1. If two SORT commands are given, --sort-section is ignored.
244 // 2. If one SORT command is given, and if it is not SORT_NONE,
245 // --sort-section is handled as an inner SORT command.
246 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
247 // 4. If no SORT command is given, sort according to --sort-section.
248 InputSectionData **Begin = I->Sections.data() + SizeBefore;
249 InputSectionData **End = I->Sections.data() + I->Sections.size();
250 if (Pat.SortOuter != SortSectionPolicy::None) {
251 if (Pat.SortInner == SortSectionPolicy::Default)
252 sortSections(Begin, End, Config->SortSection);
254 sortSections(Begin, End, Pat.SortInner);
255 sortSections(Begin, End, Pat.SortOuter);
260 template <class ELFT>
261 void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
262 for (InputSectionBase<ELFT> *S : V) {
268 template <class ELFT>
269 std::vector<InputSectionBase<ELFT> *>
270 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
271 std::vector<InputSectionBase<ELFT> *> Ret;
273 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
274 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
277 computeInputSections(Cmd);
278 for (InputSectionData *S : Cmd->Sections)
279 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
285 template <class ELFT>
286 void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
287 InputSectionBase<ELFT> *Sec,
289 OutputSectionBase *OutSec;
291 std::tie(OutSec, IsNew) = Factory.create(Sec, Name);
293 OutputSections->push_back(OutSec);
294 OutSec->addSection(Sec);
297 template <class ELFT>
298 void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
299 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
300 auto Iter = Opt.Commands.begin() + I;
301 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
303 // Handle symbol assignments outside of any output section.
304 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
305 addSymbol<ELFT>(Cmd);
309 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
310 // If we don't have SECTIONS then output sections have already been
311 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
312 // will not be called, so ASSERT should be evaluated now.
313 if (!Opt.HasSections)
318 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
319 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
321 // The output section name `/DISCARD/' is special.
322 // Any input section assigned to it is discarded.
323 if (Cmd->Name == "/DISCARD/") {
328 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
329 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
330 // sections satisfy a given constraint. If not, a directive is handled
331 // as if it wasn't present from the beginning.
333 // Because we'll iterate over Commands many more times, the easiest
334 // way to "make it as if it wasn't present" is to just remove it.
335 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
336 for (InputSectionBase<ELFT> *S : V)
338 Opt.Commands.erase(Iter);
343 // A directive may contain symbol definitions like this:
344 // ".foo : { ...; bar = .; }". Handle them.
345 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
346 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
347 addSymbol<ELFT>(OutCmd);
349 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
350 // is given, input sections are aligned to that value, whether the
351 // given value is larger or smaller than the original section alignment.
352 if (Cmd->SubalignExpr) {
353 uint32_t Subalign = Cmd->SubalignExpr(0);
354 for (InputSectionBase<ELFT> *S : V)
355 S->Alignment = Subalign;
358 // Add input sections to an output section.
359 for (InputSectionBase<ELFT> *S : V)
360 addSection(Factory, S, Cmd->Name);
365 // Add sections that didn't match any sections command.
366 template <class ELFT>
367 void LinkerScript<ELFT>::addOrphanSections(
368 OutputSectionFactory<ELFT> &Factory) {
369 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
370 if (S->Live && !S->OutSec)
371 addSection(Factory, S, getOutputSectionName(S->Name));
374 // Sets value of a section-defined symbol. Two kinds of
375 // symbols are processed: synthetic symbols, whose value
376 // is an offset from beginning of section and regular
377 // symbols whose value is absolute.
378 template <class ELFT>
379 static void assignSectionSymbol(SymbolAssignment *Cmd,
380 typename ELFT::uint Value) {
384 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
385 Body->Section = Cmd->Expression.Section();
386 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
389 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
390 Body->Value = Cmd->Expression(Value);
393 template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
394 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
397 template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
398 if (!AlreadyOutputIS.insert(S).second)
400 bool IsTbss = isTbss<ELFT>(CurOutSec);
402 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
403 Pos = alignTo(Pos, S->Alignment);
404 S->OutSecOff = Pos - CurOutSec->Addr;
407 // Update output section size after adding each section. This is so that
408 // SIZEOF works correctly in the case below:
409 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
410 CurOutSec->Size = Pos - CurOutSec->Addr;
413 ThreadBssOffset = Pos - Dot;
418 template <class ELFT> void LinkerScript<ELFT>::flush() {
419 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
421 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
422 for (InputSection<ELFT> *I : OutSec->Sections)
425 Dot += CurOutSec->Size;
429 template <class ELFT>
430 void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
431 if (CurOutSec == Sec)
433 if (AlreadyOutputOS.count(Sec))
439 Dot = alignTo(Dot, CurOutSec->Addralign);
440 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
442 // If neither AT nor AT> is specified for an allocatable section, the linker
443 // will set the LMA such that the difference between VMA and LMA for the
444 // section is the same as the preceding output section in the same region
445 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
446 CurOutSec->setLMAOffset(LMAOffset);
449 template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
450 // This handles the assignments to symbol or to a location counter (.)
451 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
452 if (AssignCmd->Name == ".") {
453 // Update to location counter means update to section size.
454 uintX_t Val = AssignCmd->Expression(Dot);
456 error("unable to move location counter backward for: " +
459 CurOutSec->Size = Dot - CurOutSec->Addr;
462 assignSectionSymbol<ELFT>(AssignCmd, Dot);
466 // Handle BYTE(), SHORT(), LONG(), or QUAD().
467 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
468 DataCmd->Offset = Dot - CurOutSec->Addr;
469 Dot += DataCmd->Size;
470 CurOutSec->Size = Dot - CurOutSec->Addr;
474 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
475 AssertCmd->Expression(Dot);
479 // It handles single input section description command,
480 // calculates and assigns the offsets for each section and also
481 // updates the output section size.
482 auto &ICmd = cast<InputSectionDescription>(Base);
483 for (InputSectionData *ID : ICmd.Sections) {
484 // We tentatively added all synthetic sections at the beginning and removed
485 // empty ones afterwards (because there is no way to know whether they were
486 // going be empty or not other than actually running linker scripts.)
487 // We need to ignore remains of empty sections.
488 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
492 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
493 switchTo(IB->OutSec);
494 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
501 template <class ELFT>
502 static std::vector<OutputSectionBase *>
503 findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
504 std::vector<OutputSectionBase *> Ret;
505 for (OutputSectionBase *Sec : Sections)
506 if (Sec->getName() == Name)
511 // This function assigns offsets to input sections and an output section
512 // for a single sections command (e.g. ".text { *(.text); }").
513 template <class ELFT>
514 void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
516 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
517 std::vector<OutputSectionBase *> Sections =
518 findSections<ELFT>(Cmd->Name, *OutputSections);
519 if (Sections.empty())
521 switchTo(Sections[0]);
523 // Find the last section output location. We will output orphan sections
524 // there so that end symbols point to the correct location.
525 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
526 [](const std::unique_ptr<BaseCommand> &Cmd) {
527 return !isa<SymbolAssignment>(*Cmd);
530 for (auto I = Cmd->Commands.begin(); I != E; ++I)
532 for (OutputSectionBase *Base : Sections)
535 std::for_each(E, Cmd->Commands.end(),
536 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
539 template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
540 // It is common practice to use very generic linker scripts. So for any
541 // given run some of the output sections in the script will be empty.
542 // We could create corresponding empty output sections, but that would
543 // clutter the output.
544 // We instead remove trivially empty sections. The bfd linker seems even
545 // more aggressive at removing them.
546 auto Pos = std::remove_if(
547 Opt.Commands.begin(), Opt.Commands.end(),
548 [&](const std::unique_ptr<BaseCommand> &Base) {
549 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
550 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
553 Opt.Commands.erase(Pos, Opt.Commands.end());
556 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
557 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
558 if (!isa<InputSectionDescription>(*I))
563 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
564 // If the output section contains only symbol assignments, create a
565 // corresponding output section. The bfd linker seems to only create them if
566 // '.' is assigned to, but creating these section should not have any bad
567 // consequeces and gives us a section to put the symbol in.
568 uintX_t Flags = SHF_ALLOC;
569 uint32_t Type = SHT_NOBITS;
570 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
571 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
574 std::vector<OutputSectionBase *> Secs =
575 findSections<ELFT>(Cmd->Name, *OutputSections);
577 Flags = Secs[0]->Flags;
578 Type = Secs[0]->Type;
582 if (isAllSectionDescription(*Cmd))
585 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
586 OutputSections->push_back(OutSec);
590 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
591 placeOrphanSections();
593 // If output section command doesn't specify any segments,
594 // and we haven't previously assigned any section to segment,
595 // then we simply assign section to the very first load segment.
596 // Below is an example of such linker script:
597 // PHDRS { seg PT_LOAD; }
598 // SECTIONS { .aaa : { *(.aaa) } }
599 std::vector<StringRef> DefPhdrs;
601 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
602 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
603 if (FirstPtLoad != Opt.PhdrsCommands.end())
604 DefPhdrs.push_back(FirstPtLoad->Name);
606 // Walk the commands and propagate the program headers to commands that don't
607 // explicitly specify them.
608 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
609 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
612 if (Cmd->Phdrs.empty())
613 Cmd->Phdrs = DefPhdrs;
615 DefPhdrs = Cmd->Phdrs;
618 removeEmptyCommands();
621 // When placing orphan sections, we want to place them after symbol assignments
622 // so that an orphan after
626 // doesn't break the intended meaning of the begin/end symbols.
627 // We don't want to go over sections since Writer<ELFT>::sortSections is the
628 // one in charge of deciding the order of the sections.
629 // We don't want to go over alignments, since doing so in
630 // rx_sec : { *(rx_sec) }
631 // . = ALIGN(0x1000);
632 // /* The RW PT_LOAD starts here*/
633 // rw_sec : { *(rw_sec) }
634 // would mean that the RW PT_LOAD would become unaligned.
635 static bool shouldSkip(const BaseCommand &Cmd) {
636 if (isa<OutputSectionCommand>(Cmd))
638 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
641 return Assign->Name != ".";
644 // Orphan sections are sections present in the input files which are not
645 // explicitly placed into the output file by the linker script. This just
646 // places them in the order already decided in OutputSections.
647 template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
648 // The OutputSections are already in the correct order.
649 // This loops creates or moves commands as needed so that they are in the
653 // As a horrible special case, skip the first . assignment if it is before any
654 // section. We do this because it is common to set a load address by starting
655 // the script with ". = 0xabcd" and the expectation is that every section is
657 auto FirstSectionOrDotAssignment =
658 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
659 [](const std::unique_ptr<BaseCommand> &Cmd) {
660 if (isa<OutputSectionCommand>(*Cmd))
662 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
665 return Assign->Name == ".";
667 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
668 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
669 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
673 for (OutputSectionBase *Sec : *OutputSections) {
674 StringRef Name = Sec->getName();
676 // Find the last spot where we can insert a command and still get the
678 auto CmdIter = Opt.Commands.begin() + CmdIndex;
679 auto E = Opt.Commands.end();
680 while (CmdIter != E && shouldSkip(**CmdIter)) {
686 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
687 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
688 return Cmd && Cmd->Name == Name;
691 Opt.Commands.insert(CmdIter,
692 llvm::make_unique<OutputSectionCommand>(Name));
697 // Continue from where we found it.
698 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
702 template <class ELFT>
703 void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
704 // Assign addresses as instructed by linker script SECTIONS sub-commands.
707 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
708 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
709 if (Cmd->Name == ".") {
710 Dot = Cmd->Expression(Dot);
711 } else if (Cmd->Sym) {
712 assignSectionSymbol<ELFT>(Cmd, Dot);
717 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
718 Cmd->Expression(Dot);
722 auto *Cmd = cast<OutputSectionCommand>(Base.get());
724 Dot = Cmd->AddrExpr(Dot);
728 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
729 for (OutputSectionBase *Sec : *OutputSections) {
730 if (Sec->Flags & SHF_ALLOC)
731 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
736 uintX_t HeaderSize = getHeaderSize();
737 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
738 // now that we know we have space.
739 if (HeaderSize <= MinVA && !hasPhdrsCommands())
740 allocateHeaders<ELFT>(Phdrs, *OutputSections);
742 // ELF and Program headers need to be right before the first section in
743 // memory. Set their addresses accordingly.
744 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
745 Out<ELFT>::ElfHeader->Addr = MinVA;
746 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
749 // Creates program headers as instructed by PHDRS linker script command.
750 template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
751 std::vector<PhdrEntry> Ret;
753 // Process PHDRS and FILEHDR keywords because they are not
754 // real output sections and cannot be added in the following loop.
755 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
756 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
757 PhdrEntry &Phdr = Ret.back();
760 Phdr.add(Out<ELFT>::ElfHeader);
762 Phdr.add(Out<ELFT>::ProgramHeaders);
765 Phdr.p_paddr = Cmd.LMAExpr(0);
770 // Add output sections to program headers.
771 for (OutputSectionBase *Sec : *OutputSections) {
772 if (!(Sec->Flags & SHF_ALLOC))
775 // Assign headers specified by linker script
776 for (size_t Id : getPhdrIndices(Sec->getName())) {
778 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
779 Ret[Id].p_flags |= Sec->getPhdrFlags();
785 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
786 // Ignore .interp section in case we have PHDRS specification
787 // and PT_INTERP isn't listed.
788 return !Opt.PhdrsCommands.empty() &&
789 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
790 return Cmd.Type == PT_INTERP;
791 }) == Opt.PhdrsCommands.end();
794 template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
795 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
796 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
797 if (Cmd->Name == Name)
802 template <class ELFT>
803 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
804 const endianness E = ELFT::TargetEndianness;
808 *Buf = (uint8_t)Data;
811 write16<E>(Buf, Data);
814 write32<E>(Buf, Data);
817 write64<E>(Buf, Data);
820 llvm_unreachable("unsupported Size argument");
824 template <class ELFT>
825 void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
826 int I = getSectionIndex(Name);
830 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
831 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
832 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
833 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
836 template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
837 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
838 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
839 if (Cmd->LMAExpr && Cmd->Name == Name)
844 // Returns the index of the given section name in linker script
845 // SECTIONS commands. Sections are laid out as the same order as they
846 // were in the script. If a given name did not appear in the script,
847 // it returns INT_MAX, so that it will be laid out at end of file.
848 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
849 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
850 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
851 if (Cmd->Name == Name)
856 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
857 return !Opt.PhdrsCommands.empty();
860 template <class ELFT>
861 const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
863 static OutputSectionBase FakeSec("", 0, 0);
865 for (OutputSectionBase *Sec : *OutputSections)
866 if (Sec->getName() == Name)
869 error(Loc + ": undefined section " + Name);
873 // This function is essentially the same as getOutputSection(Name)->Size,
874 // but it won't print out an error message if a given section is not found.
876 // Linker script does not create an output section if its content is empty.
877 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
878 // be empty. That is why this function is different from getOutputSection().
879 template <class ELFT>
880 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
881 for (OutputSectionBase *Sec : *OutputSections)
882 if (Sec->getName() == Name)
887 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
888 return elf::getHeaderSize<ELFT>();
891 template <class ELFT>
892 uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
893 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
894 return B->getVA<ELFT>();
895 error(Loc + ": symbol not found: " + S);
899 template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
900 return Symtab<ELFT>::X->find(S) != nullptr;
903 template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
904 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
905 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
906 return DR && !DR->Section;
909 // Gets section symbol belongs to. Symbol "." doesn't belong to any
910 // specific section but isn't absolute at the same time, so we try
911 // to find suitable section for it as well.
912 template <class ELFT>
913 const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
914 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
916 if (OutputSections->empty())
918 return CurOutSec ? CurOutSec : (*OutputSections)[0];
921 return SymbolTableSection<ELFT>::getOutputSection(Sym);
924 // Returns indices of ELF headers containing specific section, identified
925 // by Name. Each index is a zero based number of ELF header listed within
926 // PHDRS {} script block.
927 template <class ELFT>
928 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
929 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
930 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
931 if (!Cmd || Cmd->Name != SectionName)
934 std::vector<size_t> Ret;
935 for (StringRef PhdrName : Cmd->Phdrs)
936 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
942 template <class ELFT>
943 size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
945 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
946 if (Cmd.Name == PhdrName)
950 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
954 class elf::ScriptParser final : public ScriptParserBase {
955 typedef void (ScriptParser::*Handler)();
958 ScriptParser(MemoryBufferRef MB)
959 : ScriptParserBase(MB),
960 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
962 void readLinkerScript();
963 void readVersionScript();
964 void readDynamicList();
967 void addFile(StringRef Path);
975 void readOutputArch();
976 void readOutputFormat();
978 void readSearchDir();
981 void readVersionScriptCommand();
983 SymbolAssignment *readAssignment(StringRef Name);
984 BytesDataCommand *readBytesDataCommand(StringRef Tok);
986 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
987 uint32_t readOutputSectionFiller(StringRef Tok);
988 std::vector<StringRef> readOutputSectionPhdrs();
989 InputSectionDescription *readInputSectionDescription(StringRef Tok);
990 StringMatcher readFilePatterns();
991 std::vector<SectionPattern> readInputSectionsList();
992 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
993 unsigned readPhdrType();
994 SortSectionPolicy readSortKind();
995 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
996 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
1001 Expr readExpr1(Expr Lhs, int MinPrec);
1002 StringRef readParenLiteral();
1004 Expr readTernary(Expr Cond);
1005 Expr readParenExpr();
1007 // For parsing version script.
1008 std::vector<SymbolVersion> readVersionExtern();
1009 void readAnonymousDeclaration();
1010 void readVersionDeclaration(StringRef VerStr);
1011 std::vector<SymbolVersion> readSymbols();
1014 ScriptConfiguration &Opt = *ScriptConfig;
1015 bool IsUnderSysroot;
1018 void ScriptParser::readDynamicList() {
1020 readAnonymousDeclaration();
1022 setError("EOF expected, but got " + next());
1025 void ScriptParser::readVersionScript() {
1026 readVersionScriptCommand();
1028 setError("EOF expected, but got " + next());
1031 void ScriptParser::readVersionScriptCommand() {
1033 readAnonymousDeclaration();
1037 while (!atEOF() && !Error && peek() != "}") {
1038 StringRef VerStr = next();
1039 if (VerStr == "{") {
1040 setError("anonymous version definition is used in "
1041 "combination with other version definitions");
1045 readVersionDeclaration(VerStr);
1049 void ScriptParser::readVersion() {
1051 readVersionScriptCommand();
1055 void ScriptParser::readLinkerScript() {
1057 StringRef Tok = next();
1061 if (Tok == "ASSERT") {
1062 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1063 } else if (Tok == "ENTRY") {
1065 } else if (Tok == "EXTERN") {
1067 } else if (Tok == "GROUP" || Tok == "INPUT") {
1069 } else if (Tok == "INCLUDE") {
1071 } else if (Tok == "OUTPUT") {
1073 } else if (Tok == "OUTPUT_ARCH") {
1075 } else if (Tok == "OUTPUT_FORMAT") {
1077 } else if (Tok == "PHDRS") {
1079 } else if (Tok == "SEARCH_DIR") {
1081 } else if (Tok == "SECTIONS") {
1083 } else if (Tok == "VERSION") {
1085 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1086 Opt.Commands.emplace_back(Cmd);
1088 setError("unknown directive: " + Tok);
1093 void ScriptParser::addFile(StringRef S) {
1094 if (IsUnderSysroot && S.startswith("/")) {
1095 SmallString<128> PathData;
1096 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1097 if (sys::fs::exists(Path)) {
1098 Driver->addFile(Saver.save(Path));
1103 if (sys::path::is_absolute(S)) {
1105 } else if (S.startswith("=")) {
1106 if (Config->Sysroot.empty())
1107 Driver->addFile(S.substr(1));
1109 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1110 } else if (S.startswith("-l")) {
1111 Driver->addLibrary(S.substr(2));
1112 } else if (sys::fs::exists(S)) {
1115 if (Optional<std::string> Path = findFromSearchPaths(S))
1116 Driver->addFile(Saver.save(*Path));
1118 setError("unable to find " + S);
1122 void ScriptParser::readAsNeeded() {
1124 bool Orig = Config->AsNeeded;
1125 Config->AsNeeded = true;
1126 while (!Error && !consume(")"))
1127 addFile(unquote(next()));
1128 Config->AsNeeded = Orig;
1131 void ScriptParser::readEntry() {
1132 // -e <symbol> takes predecence over ENTRY(<symbol>).
1134 StringRef Tok = next();
1135 if (Config->Entry.empty())
1136 Config->Entry = Tok;
1140 void ScriptParser::readExtern() {
1142 while (!Error && !consume(")"))
1143 Config->Undefined.push_back(next());
1146 void ScriptParser::readGroup() {
1148 while (!Error && !consume(")")) {
1149 StringRef Tok = next();
1150 if (Tok == "AS_NEEDED")
1153 addFile(unquote(Tok));
1157 void ScriptParser::readInclude() {
1158 StringRef Tok = unquote(next());
1160 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1161 // The file will be searched for in the current directory, and in any
1162 // directory specified with the -L option.
1163 if (sys::fs::exists(Tok)) {
1164 if (Optional<MemoryBufferRef> MB = readFile(Tok))
1168 if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1169 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1173 setError("cannot open " + Tok);
1176 void ScriptParser::readOutput() {
1177 // -o <file> takes predecence over OUTPUT(<file>).
1179 StringRef Tok = next();
1180 if (Config->OutputFile.empty())
1181 Config->OutputFile = unquote(Tok);
1185 void ScriptParser::readOutputArch() {
1186 // Error checking only for now.
1192 void ScriptParser::readOutputFormat() {
1193 // Error checking only for now.
1196 StringRef Tok = next();
1200 setError("unexpected token: " + Tok);
1209 void ScriptParser::readPhdrs() {
1211 while (!Error && !consume("}")) {
1212 StringRef Tok = next();
1213 Opt.PhdrsCommands.push_back(
1214 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1215 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1217 PhdrCmd.Type = readPhdrType();
1222 if (Tok == "FILEHDR")
1223 PhdrCmd.HasFilehdr = true;
1224 else if (Tok == "PHDRS")
1225 PhdrCmd.HasPhdrs = true;
1226 else if (Tok == "AT")
1227 PhdrCmd.LMAExpr = readParenExpr();
1228 else if (Tok == "FLAGS") {
1230 // Passing 0 for the value of dot is a bit of a hack. It means that
1231 // we accept expressions like ".|1".
1232 PhdrCmd.Flags = readExpr()(0);
1235 setError("unexpected header attribute: " + Tok);
1240 void ScriptParser::readSearchDir() {
1242 StringRef Tok = next();
1243 if (!Config->Nostdlib)
1244 Config->SearchPaths.push_back(unquote(Tok));
1248 void ScriptParser::readSections() {
1249 Opt.HasSections = true;
1250 // -no-rosegment is used to avoid placing read only non-executable sections in
1251 // their own segment. We do the same if SECTIONS command is present in linker
1252 // script. See comment for computeFlags().
1253 Config->SingleRoRx = true;
1256 while (!Error && !consume("}")) {
1257 StringRef Tok = next();
1258 BaseCommand *Cmd = readProvideOrAssignment(Tok);
1260 if (Tok == "ASSERT")
1261 Cmd = new AssertCommand(readAssert());
1263 Cmd = readOutputSectionDescription(Tok);
1265 Opt.Commands.emplace_back(Cmd);
1269 static int precedence(StringRef Op) {
1270 return StringSwitch<int>(Op)
1273 .Cases("<<", ">>", 3)
1274 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1279 StringMatcher ScriptParser::readFilePatterns() {
1280 std::vector<StringRef> V;
1281 while (!Error && !consume(")"))
1282 V.push_back(next());
1283 return StringMatcher(V);
1286 SortSectionPolicy ScriptParser::readSortKind() {
1287 if (consume("SORT") || consume("SORT_BY_NAME"))
1288 return SortSectionPolicy::Name;
1289 if (consume("SORT_BY_ALIGNMENT"))
1290 return SortSectionPolicy::Alignment;
1291 if (consume("SORT_BY_INIT_PRIORITY"))
1292 return SortSectionPolicy::Priority;
1293 if (consume("SORT_NONE"))
1294 return SortSectionPolicy::None;
1295 return SortSectionPolicy::Default;
1298 // Method reads a list of sequence of excluded files and section globs given in
1299 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1300 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1301 // The semantics of that is next:
1302 // * Include .foo.1 from every file.
1303 // * Include .foo.2 from every file but a.o
1304 // * Include .foo.3 from every file but b.o
1305 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1306 std::vector<SectionPattern> Ret;
1307 while (!Error && peek() != ")") {
1308 StringMatcher ExcludeFilePat;
1309 if (consume("EXCLUDE_FILE")) {
1311 ExcludeFilePat = readFilePatterns();
1314 std::vector<StringRef> V;
1315 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1316 V.push_back(next());
1319 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1321 setError("section pattern is expected");
1326 // Reads contents of "SECTIONS" directive. That directive contains a
1327 // list of glob patterns for input sections. The grammar is as follows.
1329 // <patterns> ::= <section-list>
1330 // | <sort> "(" <section-list> ")"
1331 // | <sort> "(" <sort> "(" <section-list> ")" ")"
1333 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1334 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1336 // <section-list> is parsed by readInputSectionsList().
1337 InputSectionDescription *
1338 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1339 auto *Cmd = new InputSectionDescription(FilePattern);
1341 while (!Error && !consume(")")) {
1342 SortSectionPolicy Outer = readSortKind();
1343 SortSectionPolicy Inner = SortSectionPolicy::Default;
1344 std::vector<SectionPattern> V;
1345 if (Outer != SortSectionPolicy::Default) {
1347 Inner = readSortKind();
1348 if (Inner != SortSectionPolicy::Default) {
1350 V = readInputSectionsList();
1353 V = readInputSectionsList();
1357 V = readInputSectionsList();
1360 for (SectionPattern &Pat : V) {
1361 Pat.SortInner = Inner;
1362 Pat.SortOuter = Outer;
1365 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1370 InputSectionDescription *
1371 ScriptParser::readInputSectionDescription(StringRef Tok) {
1372 // Input section wildcard can be surrounded by KEEP.
1373 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1374 if (Tok == "KEEP") {
1376 StringRef FilePattern = next();
1377 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1379 Opt.KeptSections.push_back(Cmd);
1382 return readInputSectionRules(Tok);
1385 void ScriptParser::readSort() {
1387 expect("CONSTRUCTORS");
1391 Expr ScriptParser::readAssert() {
1393 Expr E = readExpr();
1395 StringRef Msg = unquote(next());
1397 return [=](uint64_t Dot) {
1398 uint64_t V = E(Dot);
1405 // Reads a FILL(expr) command. We handle the FILL command as an
1406 // alias for =fillexp section attribute, which is different from
1407 // what GNU linkers do.
1408 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1409 uint32_t ScriptParser::readFill() {
1411 uint32_t V = readOutputSectionFiller(next());
1417 OutputSectionCommand *
1418 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1419 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1420 Cmd->Location = getCurrentLocation();
1422 // Read an address expression.
1423 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1425 Cmd->AddrExpr = readExpr();
1430 Cmd->LMAExpr = readParenExpr();
1431 if (consume("ALIGN"))
1432 Cmd->AlignExpr = readParenExpr();
1433 if (consume("SUBALIGN"))
1434 Cmd->SubalignExpr = readParenExpr();
1436 // Parse constraints.
1437 if (consume("ONLY_IF_RO"))
1438 Cmd->Constraint = ConstraintKind::ReadOnly;
1439 if (consume("ONLY_IF_RW"))
1440 Cmd->Constraint = ConstraintKind::ReadWrite;
1443 while (!Error && !consume("}")) {
1444 StringRef Tok = next();
1445 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
1446 Cmd->Commands.emplace_back(Assignment);
1447 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
1448 Cmd->Commands.emplace_back(Data);
1449 } else if (Tok == "ASSERT") {
1450 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1452 } else if (Tok == "FILL") {
1453 Cmd->Filler = readFill();
1454 } else if (Tok == "SORT") {
1456 } else if (peek() == "(") {
1457 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1459 setError("unknown command " + Tok);
1462 Cmd->Phdrs = readOutputSectionPhdrs();
1465 Cmd->Filler = readOutputSectionFiller(next());
1466 else if (peek().startswith("="))
1467 Cmd->Filler = readOutputSectionFiller(next().drop_front());
1472 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1473 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1475 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1476 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1477 // as 32-bit big-endian values. We will do the same as ld.gold does
1478 // because it's simpler than what ld.bfd does.
1479 uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
1481 if (!Tok.getAsInteger(0, V))
1483 setError("invalid filler expression: " + Tok);
1487 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1489 SymbolAssignment *Cmd = readAssignment(next());
1490 Cmd->Provide = Provide;
1491 Cmd->Hidden = Hidden;
1497 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1498 SymbolAssignment *Cmd = nullptr;
1499 if (peek() == "=" || peek() == "+=") {
1500 Cmd = readAssignment(Tok);
1502 } else if (Tok == "PROVIDE") {
1503 Cmd = readProvideHidden(true, false);
1504 } else if (Tok == "HIDDEN") {
1505 Cmd = readProvideHidden(false, true);
1506 } else if (Tok == "PROVIDE_HIDDEN") {
1507 Cmd = readProvideHidden(true, true);
1512 static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
1515 return ScriptBase->getSymbolValue(Loc, S);
1518 static bool isAbsolute(StringRef S) {
1521 return ScriptBase->isAbsolute(S);
1524 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1525 StringRef Op = next();
1527 assert(Op == "=" || Op == "+=");
1528 if (consume("ABSOLUTE")) {
1529 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1530 // Call readExpr1 to read the whole expression.
1531 E = readExpr1(readParenExpr(), 0);
1532 E.IsAbsolute = [] { return true; };
1537 std::string Loc = getCurrentLocation();
1538 E = [=](uint64_t Dot) {
1539 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1542 return new SymbolAssignment(Name, E);
1545 // This is an operator-precedence parser to parse a linker
1546 // script expression.
1547 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1549 static Expr combine(StringRef Op, Expr L, Expr R) {
1551 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1553 return [=](uint64_t Dot) -> uint64_t {
1554 uint64_t RHS = R(Dot);
1556 error("division by zero");
1559 return L(Dot) / RHS;
1563 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1564 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1566 const OutputSectionBase *S = L.Section();
1567 return S ? S : R.Section();
1570 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1572 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1574 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
1576 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1578 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1580 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1582 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1584 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1586 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1588 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1590 return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
1591 llvm_unreachable("invalid operator");
1594 // This is a part of the operator-precedence parser. This function
1595 // assumes that the remaining token stream starts with an operator.
1596 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1597 while (!atEOF() && !Error) {
1598 // Read an operator and an expression.
1600 return readTernary(Lhs);
1601 StringRef Op1 = peek();
1602 if (precedence(Op1) < MinPrec)
1605 Expr Rhs = readPrimary();
1607 // Evaluate the remaining part of the expression first if the
1608 // next operator has greater precedence than the previous one.
1609 // For example, if we have read "+" and "3", and if the next
1610 // operator is "*", then we'll evaluate 3 * ... part first.
1612 StringRef Op2 = peek();
1613 if (precedence(Op2) <= precedence(Op1))
1615 Rhs = readExpr1(Rhs, precedence(Op2));
1618 Lhs = combine(Op1, Lhs, Rhs);
1623 uint64_t static getConstant(StringRef S) {
1624 if (S == "COMMONPAGESIZE")
1625 return Target->PageSize;
1626 if (S == "MAXPAGESIZE")
1627 return Config->MaxPageSize;
1628 error("unknown constant: " + S);
1632 // Parses Tok as an integer. Returns true if successful.
1633 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1634 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1635 // "M" (mega) prefixes.
1636 static bool readInteger(StringRef Tok, uint64_t &Result) {
1638 if (Tok.startswith("-")) {
1639 if (!readInteger(Tok.substr(1), Result))
1646 if (Tok.startswith_lower("0x"))
1647 return !Tok.substr(2).getAsInteger(16, Result);
1648 if (Tok.endswith_lower("H"))
1649 return !Tok.drop_back().getAsInteger(16, Result);
1653 if (Tok.endswith_lower("K")) {
1655 Tok = Tok.drop_back();
1656 } else if (Tok.endswith_lower("M")) {
1657 Suffix = 1024 * 1024;
1658 Tok = Tok.drop_back();
1660 if (Tok.getAsInteger(10, Result))
1666 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1667 int Size = StringSwitch<unsigned>(Tok)
1676 return new BytesDataCommand(readParenExpr(), Size);
1679 StringRef ScriptParser::readParenLiteral() {
1681 StringRef Tok = next();
1686 Expr ScriptParser::readPrimary() {
1688 return readParenExpr();
1690 StringRef Tok = next();
1691 std::string Location = getCurrentLocation();
1694 Expr E = readPrimary();
1695 return [=](uint64_t Dot) { return ~E(Dot); };
1698 Expr E = readPrimary();
1699 return [=](uint64_t Dot) { return -E(Dot); };
1702 // Built-in functions are parsed here.
1703 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1704 if (Tok == "ADDR") {
1705 StringRef Name = readParenLiteral();
1706 return {[=](uint64_t Dot) {
1707 return ScriptBase->getOutputSection(Location, Name)->Addr;
1709 [=] { return false; },
1710 [=] { return ScriptBase->getOutputSection(Location, Name); }};
1712 if (Tok == "LOADADDR") {
1713 StringRef Name = readParenLiteral();
1714 return [=](uint64_t Dot) {
1715 return ScriptBase->getOutputSection(Location, Name)->getLMA();
1718 if (Tok == "ASSERT")
1719 return readAssert();
1720 if (Tok == "ALIGN") {
1722 Expr E = readExpr();
1724 Expr E2 = readExpr();
1726 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1729 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1731 if (Tok == "CONSTANT") {
1732 StringRef Name = readParenLiteral();
1733 return [=](uint64_t Dot) { return getConstant(Name); };
1735 if (Tok == "DEFINED") {
1736 StringRef Name = readParenLiteral();
1737 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
1739 if (Tok == "SEGMENT_START") {
1743 Expr E = readExpr();
1745 return [=](uint64_t Dot) { return E(Dot); };
1747 if (Tok == "DATA_SEGMENT_ALIGN") {
1749 Expr E = readExpr();
1753 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1755 if (Tok == "DATA_SEGMENT_END") {
1759 return [](uint64_t Dot) { return Dot; };
1761 // GNU linkers implements more complicated logic to handle
1762 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1763 // the next page boundary for simplicity.
1764 if (Tok == "DATA_SEGMENT_RELRO_END") {
1770 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1772 if (Tok == "SIZEOF") {
1773 StringRef Name = readParenLiteral();
1774 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1776 if (Tok == "ALIGNOF") {
1777 StringRef Name = readParenLiteral();
1778 return [=](uint64_t Dot) {
1779 return ScriptBase->getOutputSection(Location, Name)->Addralign;
1782 if (Tok == "SIZEOF_HEADERS")
1783 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1785 // Tok is a literal number.
1787 if (readInteger(Tok, V))
1788 return [=](uint64_t Dot) { return V; };
1790 // Tok is a symbol name.
1791 if (Tok != "." && !isValidCIdentifier(Tok))
1792 setError("malformed number: " + Tok);
1793 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
1794 [=] { return isAbsolute(Tok); },
1795 [=] { return ScriptBase->getSymbolSection(Tok); }};
1798 Expr ScriptParser::readTernary(Expr Cond) {
1799 Expr L = readExpr();
1801 Expr R = readExpr();
1802 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1805 Expr ScriptParser::readParenExpr() {
1807 Expr E = readExpr();
1812 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1813 std::vector<StringRef> Phdrs;
1814 while (!Error && peek().startswith(":")) {
1815 StringRef Tok = next();
1816 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1821 // Read a program header type name. The next token must be a
1822 // name of a program header type or a constant (e.g. "0x3").
1823 unsigned ScriptParser::readPhdrType() {
1824 StringRef Tok = next();
1826 if (readInteger(Tok, Val))
1829 unsigned Ret = StringSwitch<unsigned>(Tok)
1830 .Case("PT_NULL", PT_NULL)
1831 .Case("PT_LOAD", PT_LOAD)
1832 .Case("PT_DYNAMIC", PT_DYNAMIC)
1833 .Case("PT_INTERP", PT_INTERP)
1834 .Case("PT_NOTE", PT_NOTE)
1835 .Case("PT_SHLIB", PT_SHLIB)
1836 .Case("PT_PHDR", PT_PHDR)
1837 .Case("PT_TLS", PT_TLS)
1838 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1839 .Case("PT_GNU_STACK", PT_GNU_STACK)
1840 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1841 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1842 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1843 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1846 if (Ret == (unsigned)-1) {
1847 setError("invalid program header type: " + Tok);
1853 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1854 void ScriptParser::readAnonymousDeclaration() {
1855 // Read global symbols first. "global:" is default, so if there's
1856 // no label, we assume global symbols.
1857 if (consume("global:") || peek() != "local:")
1858 Config->VersionScriptGlobals = readSymbols();
1865 void ScriptParser::readLocals() {
1866 if (!consume("local:"))
1868 std::vector<SymbolVersion> Locals = readSymbols();
1869 for (SymbolVersion V : Locals) {
1870 if (V.Name == "*") {
1871 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1874 Config->VersionScriptLocals.push_back(V);
1878 // Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
1879 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1880 // Identifiers start at 2 because 0 and 1 are reserved
1881 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1882 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
1883 Config->VersionDefinitions.push_back({VerStr, VersionId});
1885 // Read global symbols.
1886 if (consume("global:") || peek() != "local:")
1887 Config->VersionDefinitions.back().Globals = readSymbols();
1892 // Each version may have a parent version. For example, "Ver2"
1893 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1894 // as a parent. This version hierarchy is, probably against your
1895 // instinct, purely for hint; the runtime doesn't care about it
1896 // at all. In LLD, we simply ignore it.
1902 // Reads a list of symbols for a versions cript.
1903 std::vector<SymbolVersion> ScriptParser::readSymbols() {
1904 std::vector<SymbolVersion> Ret;
1906 if (consume("extern")) {
1907 for (SymbolVersion V : readVersionExtern())
1912 if (peek() == "}" || peek() == "local:" || Error)
1914 StringRef Tok = next();
1915 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
1921 // Reads an "extern C++" directive, e.g.,
1922 // "extern "C++" { ns::*; "f(int, double)"; };"
1923 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1924 StringRef Tok = next();
1925 bool IsCXX = Tok == "\"C++\"";
1926 if (!IsCXX && Tok != "\"C\"")
1927 setError("Unknown language");
1930 std::vector<SymbolVersion> Ret;
1931 while (!Error && peek() != "}") {
1932 StringRef Tok = next();
1933 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1934 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1943 void elf::readLinkerScript(MemoryBufferRef MB) {
1944 ScriptParser(MB).readLinkerScript();
1947 void elf::readVersionScript(MemoryBufferRef MB) {
1948 ScriptParser(MB).readVersionScript();
1951 void elf::readDynamicList(MemoryBufferRef MB) {
1952 ScriptParser(MB).readDynamicList();
1955 template class elf::LinkerScript<ELF32LE>;
1956 template class elf::LinkerScript<ELF32BE>;
1957 template class elf::LinkerScript<ELF64LE>;
1958 template class elf::LinkerScript<ELF64BE>;