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 void addRegular(SymbolAssignment *Cmd) {
60 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
61 Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
62 0, 0, STB_GLOBAL, nullptr, nullptr);
63 Cmd->Sym = Sym->body();
65 // If we have no SECTIONS then we don't have '.' and don't call
66 // assignAddresses(). We calculate symbol value immediately in this case.
67 if (!ScriptConfig->HasSections)
68 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
71 template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
72 // If we have SECTIONS block then output sections haven't been created yet.
73 const OutputSectionBase *Sec =
74 ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
75 Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
76 Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
77 Cmd->Sym = Sym->body();
79 // If we already know section then we can calculate symbol value immediately.
81 cast<DefinedSynthetic>(Cmd->Sym)->Value = Cmd->Expression(0) - Sec->Addr;
84 static bool isUnderSysroot(StringRef Path) {
85 if (Config->Sysroot == "")
87 for (; !Path.empty(); Path = sys::path::parent_path(Path))
88 if (sys::fs::equivalent(Config->Sysroot, Path))
93 template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
94 if (Cmd->Expression.IsAbsolute())
95 addRegular<ELFT>(Cmd);
97 addSynthetic<ELFT>(Cmd);
99 // If a symbol was in PROVIDE(), we need to define it only when
100 // it is an undefined symbol.
101 template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
102 if (Cmd->Name == ".")
106 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
107 return B && B->isUndefined();
110 bool SymbolAssignment::classof(const BaseCommand *C) {
111 return C->Kind == AssignmentKind;
114 bool OutputSectionCommand::classof(const BaseCommand *C) {
115 return C->Kind == OutputSectionKind;
118 bool InputSectionDescription::classof(const BaseCommand *C) {
119 return C->Kind == InputSectionKind;
122 bool AssertCommand::classof(const BaseCommand *C) {
123 return C->Kind == AssertKind;
126 bool BytesDataCommand::classof(const BaseCommand *C) {
127 return C->Kind == BytesDataKind;
130 template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
131 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
133 template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
135 return sys::path::filename(S->getFile()->getName());
139 template <class ELFT>
140 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
141 for (InputSectionDescription *ID : Opt.KeptSections)
142 if (ID->FilePat.match(basename(S)))
143 for (SectionPattern &P : ID->SectionPatterns)
144 if (P.SectionPat.match(S->Name))
149 static bool comparePriority(InputSectionData *A, InputSectionData *B) {
150 return getPriority(A->Name) < getPriority(B->Name);
153 static bool compareName(InputSectionData *A, InputSectionData *B) {
154 return A->Name < B->Name;
157 static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
158 // ">" is not a mistake. Larger alignments are placed before smaller
159 // alignments in order to reduce the amount of padding necessary.
160 // This is compatible with GNU.
161 return A->Alignment > B->Alignment;
164 static std::function<bool(InputSectionData *, InputSectionData *)>
165 getComparator(SortSectionPolicy K) {
167 case SortSectionPolicy::Alignment:
168 return compareAlignment;
169 case SortSectionPolicy::Name:
171 case SortSectionPolicy::Priority:
172 return comparePriority;
174 llvm_unreachable("unknown sort policy");
178 template <class ELFT>
179 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
180 ConstraintKind Kind) {
181 if (Kind == ConstraintKind::NoConstraint)
183 bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
184 auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
185 return Sec->Flags & SHF_WRITE;
187 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
188 (!IsRW && Kind == ConstraintKind::ReadOnly);
191 static void sortSections(InputSectionData **Begin, InputSectionData **End,
192 SortSectionPolicy K) {
193 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
194 std::stable_sort(Begin, End, getComparator(K));
197 // Compute and remember which sections the InputSectionDescription matches.
198 template <class ELFT>
199 void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
200 // Collects all sections that satisfy constraints of I
201 // and attach them to I.
202 for (SectionPattern &Pat : I->SectionPatterns) {
203 size_t SizeBefore = I->Sections.size();
205 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
206 if (!S->Live || S->Assigned)
209 StringRef Filename = basename(S);
210 if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
212 if (!Pat.SectionPat.match(S->Name))
214 I->Sections.push_back(S);
218 // Sort sections as instructed by SORT-family commands and --sort-section
219 // option. Because SORT-family commands can be nested at most two depth
220 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
221 // line option is respected even if a SORT command is given, the exact
222 // behavior we have here is a bit complicated. Here are the rules.
224 // 1. If two SORT commands are given, --sort-section is ignored.
225 // 2. If one SORT command is given, and if it is not SORT_NONE,
226 // --sort-section is handled as an inner SORT command.
227 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
228 // 4. If no SORT command is given, sort according to --sort-section.
229 InputSectionData **Begin = I->Sections.data() + SizeBefore;
230 InputSectionData **End = I->Sections.data() + I->Sections.size();
231 if (Pat.SortOuter != SortSectionPolicy::None) {
232 if (Pat.SortInner == SortSectionPolicy::Default)
233 sortSections(Begin, End, Config->SortSection);
235 sortSections(Begin, End, Pat.SortInner);
236 sortSections(Begin, End, Pat.SortOuter);
241 template <class ELFT>
242 void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
243 for (InputSectionBase<ELFT> *S : V) {
249 template <class ELFT>
250 std::vector<InputSectionBase<ELFT> *>
251 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
252 std::vector<InputSectionBase<ELFT> *> Ret;
254 for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
255 auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
258 computeInputSections(Cmd);
259 for (InputSectionData *S : Cmd->Sections)
260 Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
266 template <class ELFT>
267 void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
268 InputSectionBase<ELFT> *Sec,
270 OutputSectionBase *OutSec;
272 std::tie(OutSec, IsNew) = Factory.create(Sec, Name);
274 OutputSections->push_back(OutSec);
275 OutSec->addSection(Sec);
278 template <class ELFT>
279 void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
280 for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
281 auto Iter = Opt.Commands.begin() + I;
282 const std::unique_ptr<BaseCommand> &Base1 = *Iter;
284 // Handle symbol assignments outside of any output section.
285 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
286 if (shouldDefine<ELFT>(Cmd))
287 addSymbol<ELFT>(Cmd);
291 if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
292 // If we don't have SECTIONS then output sections have already been
293 // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
294 // will not be called, so ASSERT should be evaluated now.
295 if (!Opt.HasSections)
300 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
301 std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
303 // The output section name `/DISCARD/' is special.
304 // Any input section assigned to it is discarded.
305 if (Cmd->Name == "/DISCARD/") {
310 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
311 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
312 // sections satisfy a given constraint. If not, a directive is handled
313 // as if it wasn't present from the beginning.
315 // Because we'll iterate over Commands many more times, the easiest
316 // way to "make it as if it wasn't present" is to just remove it.
317 if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
318 for (InputSectionBase<ELFT> *S : V)
320 Opt.Commands.erase(Iter);
325 // A directive may contain symbol definitions like this:
326 // ".foo : { ...; bar = .; }". Handle them.
327 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
328 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
329 if (shouldDefine<ELFT>(OutCmd))
330 addSymbol<ELFT>(OutCmd);
332 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
333 // is given, input sections are aligned to that value, whether the
334 // given value is larger or smaller than the original section alignment.
335 if (Cmd->SubalignExpr) {
336 uint32_t Subalign = Cmd->SubalignExpr(0);
337 for (InputSectionBase<ELFT> *S : V)
338 S->Alignment = Subalign;
341 // Add input sections to an output section.
342 for (InputSectionBase<ELFT> *S : V)
343 addSection(Factory, S, Cmd->Name);
348 // Add sections that didn't match any sections command.
349 template <class ELFT>
350 void LinkerScript<ELFT>::addOrphanSections(
351 OutputSectionFactory<ELFT> &Factory) {
352 for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
353 if (S->Live && !S->OutSec)
354 addSection(Factory, S, getOutputSectionName(S->Name));
357 // Sets value of a section-defined symbol. Two kinds of
358 // symbols are processed: synthetic symbols, whose value
359 // is an offset from beginning of section and regular
360 // symbols whose value is absolute.
361 template <class ELFT>
362 static void assignSectionSymbol(SymbolAssignment *Cmd,
363 typename ELFT::uint Value) {
367 if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) {
368 Body->Section = Cmd->Expression.Section();
369 Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
372 auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
373 Body->Value = Cmd->Expression(Value);
376 template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
377 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
380 template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
381 if (!AlreadyOutputIS.insert(S).second)
383 bool IsTbss = isTbss<ELFT>(CurOutSec);
385 uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
386 Pos = alignTo(Pos, S->Alignment);
387 S->OutSecOff = Pos - CurOutSec->Addr;
390 // Update output section size after adding each section. This is so that
391 // SIZEOF works correctly in the case below:
392 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
393 CurOutSec->Size = Pos - CurOutSec->Addr;
396 ThreadBssOffset = Pos - Dot;
401 template <class ELFT> void LinkerScript<ELFT>::flush() {
402 if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
404 if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
405 for (InputSection<ELFT> *I : OutSec->Sections)
408 Dot += CurOutSec->Size;
412 template <class ELFT>
413 void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
414 if (CurOutSec == Sec)
416 if (AlreadyOutputOS.count(Sec))
422 Dot = alignTo(Dot, CurOutSec->Addralign);
423 CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
425 // If neither AT nor AT> is specified for an allocatable section, the linker
426 // will set the LMA such that the difference between VMA and LMA for the
427 // section is the same as the preceding output section in the same region
428 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
429 CurOutSec->setLMAOffset(LMAOffset);
432 template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
433 // This handles the assignments to symbol or to a location counter (.)
434 if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
435 if (AssignCmd->Name == ".") {
436 // Update to location counter means update to section size.
437 uintX_t Val = AssignCmd->Expression(Dot);
439 error("unable to move location counter backward for: " +
442 CurOutSec->Size = Dot - CurOutSec->Addr;
445 assignSectionSymbol<ELFT>(AssignCmd, Dot);
449 // Handle BYTE(), SHORT(), LONG(), or QUAD().
450 if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
451 DataCmd->Offset = Dot - CurOutSec->Addr;
452 Dot += DataCmd->Size;
453 CurOutSec->Size = Dot - CurOutSec->Addr;
457 if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
458 AssertCmd->Expression(Dot);
462 // It handles single input section description command,
463 // calculates and assigns the offsets for each section and also
464 // updates the output section size.
465 auto &ICmd = cast<InputSectionDescription>(Base);
466 for (InputSectionData *ID : ICmd.Sections) {
467 // We tentatively added all synthetic sections at the beginning and removed
468 // empty ones afterwards (because there is no way to know whether they were
469 // going be empty or not other than actually running linker scripts.)
470 // We need to ignore remains of empty sections.
471 if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
475 auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
476 switchTo(IB->OutSec);
477 if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
484 template <class ELFT>
485 static std::vector<OutputSectionBase *>
486 findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
487 std::vector<OutputSectionBase *> Ret;
488 for (OutputSectionBase *Sec : Sections)
489 if (Sec->getName() == Name)
494 // This function assigns offsets to input sections and an output section
495 // for a single sections command (e.g. ".text { *(.text); }").
496 template <class ELFT>
497 void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
499 LMAOffset = Cmd->LMAExpr(Dot) - Dot;
500 std::vector<OutputSectionBase *> Sections =
501 findSections<ELFT>(Cmd->Name, *OutputSections);
502 if (Sections.empty())
504 switchTo(Sections[0]);
506 // Find the last section output location. We will output orphan sections
507 // there so that end symbols point to the correct location.
508 auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
509 [](const std::unique_ptr<BaseCommand> &Cmd) {
510 return !isa<SymbolAssignment>(*Cmd);
513 for (auto I = Cmd->Commands.begin(); I != E; ++I)
515 for (OutputSectionBase *Base : Sections)
518 std::for_each(E, Cmd->Commands.end(),
519 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
522 template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
523 // It is common practice to use very generic linker scripts. So for any
524 // given run some of the output sections in the script will be empty.
525 // We could create corresponding empty output sections, but that would
526 // clutter the output.
527 // We instead remove trivially empty sections. The bfd linker seems even
528 // more aggressive at removing them.
529 auto Pos = std::remove_if(
530 Opt.Commands.begin(), Opt.Commands.end(),
531 [&](const std::unique_ptr<BaseCommand> &Base) {
532 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
533 return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
536 Opt.Commands.erase(Pos, Opt.Commands.end());
539 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
540 for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
541 if (!isa<InputSectionDescription>(*I))
546 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
547 // If the output section contains only symbol assignments, create a
548 // corresponding output section. The bfd linker seems to only create them if
549 // '.' is assigned to, but creating these section should not have any bad
550 // consequeces and gives us a section to put the symbol in.
551 uintX_t Flags = SHF_ALLOC;
552 uint32_t Type = SHT_NOBITS;
553 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
554 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
557 std::vector<OutputSectionBase *> Secs =
558 findSections<ELFT>(Cmd->Name, *OutputSections);
560 Flags = Secs[0]->Flags;
561 Type = Secs[0]->Type;
565 if (isAllSectionDescription(*Cmd))
568 auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
569 OutputSections->push_back(OutSec);
573 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
574 placeOrphanSections();
576 // If output section command doesn't specify any segments,
577 // and we haven't previously assigned any section to segment,
578 // then we simply assign section to the very first load segment.
579 // Below is an example of such linker script:
580 // PHDRS { seg PT_LOAD; }
581 // SECTIONS { .aaa : { *(.aaa) } }
582 std::vector<StringRef> DefPhdrs;
584 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
585 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
586 if (FirstPtLoad != Opt.PhdrsCommands.end())
587 DefPhdrs.push_back(FirstPtLoad->Name);
589 // Walk the commands and propagate the program headers to commands that don't
590 // explicitly specify them.
591 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
592 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
595 if (Cmd->Phdrs.empty())
596 Cmd->Phdrs = DefPhdrs;
598 DefPhdrs = Cmd->Phdrs;
601 removeEmptyCommands();
604 // When placing orphan sections, we want to place them after symbol assignments
605 // so that an orphan after
609 // doesn't break the intended meaning of the begin/end symbols.
610 // We don't want to go over sections since Writer<ELFT>::sortSections is the
611 // one in charge of deciding the order of the sections.
612 // We don't want to go over alignments, since doing so in
613 // rx_sec : { *(rx_sec) }
614 // . = ALIGN(0x1000);
615 // /* The RW PT_LOAD starts here*/
616 // rw_sec : { *(rw_sec) }
617 // would mean that the RW PT_LOAD would become unaligned.
618 static bool shouldSkip(const BaseCommand &Cmd) {
619 if (isa<OutputSectionCommand>(Cmd))
621 const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
624 return Assign->Name != ".";
627 // Orphan sections are sections present in the input files which are not
628 // explicitly placed into the output file by the linker script. This just
629 // places them in the order already decided in OutputSections.
630 template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
631 // The OutputSections are already in the correct order.
632 // This loops creates or moves commands as needed so that they are in the
636 // As a horrible special case, skip the first . assignment if it is before any
637 // section. We do this because it is common to set a load address by starting
638 // the script with ". = 0xabcd" and the expectation is that every section is
640 auto FirstSectionOrDotAssignment =
641 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
642 [](const std::unique_ptr<BaseCommand> &Cmd) {
643 if (isa<OutputSectionCommand>(*Cmd))
645 const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
648 return Assign->Name == ".";
650 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
651 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
652 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
656 for (OutputSectionBase *Sec : *OutputSections) {
657 StringRef Name = Sec->getName();
659 // Find the last spot where we can insert a command and still get the
661 auto CmdIter = Opt.Commands.begin() + CmdIndex;
662 auto E = Opt.Commands.end();
663 while (CmdIter != E && shouldSkip(**CmdIter)) {
669 std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
670 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
671 return Cmd && Cmd->Name == Name;
674 Opt.Commands.insert(CmdIter,
675 llvm::make_unique<OutputSectionCommand>(Name));
680 // Continue from where we found it.
681 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
685 template <class ELFT>
686 void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
687 // Assign addresses as instructed by linker script SECTIONS sub-commands.
690 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
691 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
692 if (Cmd->Name == ".") {
693 Dot = Cmd->Expression(Dot);
694 } else if (Cmd->Sym) {
695 assignSectionSymbol<ELFT>(Cmd, Dot);
700 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
701 Cmd->Expression(Dot);
705 auto *Cmd = cast<OutputSectionCommand>(Base.get());
707 Dot = Cmd->AddrExpr(Dot);
711 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
712 for (OutputSectionBase *Sec : *OutputSections) {
713 if (Sec->Flags & SHF_ALLOC)
714 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
719 uintX_t HeaderSize = getHeaderSize();
720 // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
721 // now that we know we have space.
722 if (HeaderSize <= MinVA && !hasPhdrsCommands())
723 allocateHeaders<ELFT>(Phdrs, *OutputSections);
725 // ELF and Program headers need to be right before the first section in
726 // memory. Set their addresses accordingly.
727 MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
728 Out<ELFT>::ElfHeader->Addr = MinVA;
729 Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
732 // Creates program headers as instructed by PHDRS linker script command.
733 template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
734 std::vector<PhdrEntry> Ret;
736 // Process PHDRS and FILEHDR keywords because they are not
737 // real output sections and cannot be added in the following loop.
738 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
739 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
740 PhdrEntry &Phdr = Ret.back();
743 Phdr.add(Out<ELFT>::ElfHeader);
745 Phdr.add(Out<ELFT>::ProgramHeaders);
748 Phdr.p_paddr = Cmd.LMAExpr(0);
753 // Add output sections to program headers.
754 for (OutputSectionBase *Sec : *OutputSections) {
755 if (!(Sec->Flags & SHF_ALLOC))
758 // Assign headers specified by linker script
759 for (size_t Id : getPhdrIndices(Sec->getName())) {
761 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
762 Ret[Id].p_flags |= Sec->getPhdrFlags();
768 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
769 // Ignore .interp section in case we have PHDRS specification
770 // and PT_INTERP isn't listed.
771 return !Opt.PhdrsCommands.empty() &&
772 llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
773 return Cmd.Type == PT_INTERP;
774 }) == Opt.PhdrsCommands.end();
777 template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
778 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
779 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
780 if (Cmd->Name == Name)
785 template <class ELFT>
786 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
787 const endianness E = ELFT::TargetEndianness;
791 *Buf = (uint8_t)Data;
794 write16<E>(Buf, Data);
797 write32<E>(Buf, Data);
800 write64<E>(Buf, Data);
803 llvm_unreachable("unsupported Size argument");
807 template <class ELFT>
808 void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
809 int I = getSectionIndex(Name);
813 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
814 for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
815 if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
816 writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
819 template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
820 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
821 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
822 if (Cmd->LMAExpr && Cmd->Name == Name)
827 // Returns the index of the given section name in linker script
828 // SECTIONS commands. Sections are laid out as the same order as they
829 // were in the script. If a given name did not appear in the script,
830 // it returns INT_MAX, so that it will be laid out at end of file.
831 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
832 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
833 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
834 if (Cmd->Name == Name)
839 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
840 return !Opt.PhdrsCommands.empty();
843 template <class ELFT>
844 const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
846 static OutputSectionBase FakeSec("", 0, 0);
848 for (OutputSectionBase *Sec : *OutputSections)
849 if (Sec->getName() == Name)
852 error(Loc + ": undefined section " + Name);
856 // This function is essentially the same as getOutputSection(Name)->Size,
857 // but it won't print out an error message if a given section is not found.
859 // Linker script does not create an output section if its content is empty.
860 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
861 // be empty. That is why this function is different from getOutputSection().
862 template <class ELFT>
863 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
864 for (OutputSectionBase *Sec : *OutputSections)
865 if (Sec->getName() == Name)
870 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
871 return elf::getHeaderSize<ELFT>();
874 template <class ELFT>
875 uint64_t LinkerScript<ELFT>::getSymbolValue(const Twine &Loc, StringRef S) {
876 if (SymbolBody *B = Symtab<ELFT>::X->find(S))
877 return B->getVA<ELFT>();
878 error(Loc + ": symbol not found: " + S);
882 template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
883 return Symtab<ELFT>::X->find(S) != nullptr;
886 template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
887 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
888 auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
889 return DR && !DR->Section;
892 // Gets section symbol belongs to. Symbol "." doesn't belong to any
893 // specific section but isn't absolute at the same time, so we try
894 // to find suitable section for it as well.
895 template <class ELFT>
896 const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
897 SymbolBody *Sym = Symtab<ELFT>::X->find(S);
899 if (OutputSections->empty())
901 return CurOutSec ? CurOutSec : (*OutputSections)[0];
904 if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
905 return DR->Section ? DR->Section->OutSec : nullptr;
906 if (auto *DS = dyn_cast_or_null<DefinedSynthetic>(Sym))
912 // Returns indices of ELF headers containing specific section, identified
913 // by Name. Each index is a zero based number of ELF header listed within
914 // PHDRS {} script block.
915 template <class ELFT>
916 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
917 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
918 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
919 if (!Cmd || Cmd->Name != SectionName)
922 std::vector<size_t> Ret;
923 for (StringRef PhdrName : Cmd->Phdrs)
924 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
930 template <class ELFT>
931 size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
933 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
934 if (Cmd.Name == PhdrName)
938 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
942 class elf::ScriptParser final : public ScriptParserBase {
943 typedef void (ScriptParser::*Handler)();
946 ScriptParser(MemoryBufferRef MB)
947 : ScriptParserBase(MB),
948 IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
950 void readLinkerScript();
951 void readVersionScript();
952 void readDynamicList();
955 void addFile(StringRef Path);
963 void readOutputArch();
964 void readOutputFormat();
966 void readSearchDir();
969 void readVersionScriptCommand();
971 SymbolAssignment *readAssignment(StringRef Name);
972 BytesDataCommand *readBytesDataCommand(StringRef Tok);
974 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
975 uint32_t readOutputSectionFiller(StringRef Tok);
976 std::vector<StringRef> readOutputSectionPhdrs();
977 InputSectionDescription *readInputSectionDescription(StringRef Tok);
978 StringMatcher readFilePatterns();
979 std::vector<SectionPattern> readInputSectionsList();
980 InputSectionDescription *readInputSectionRules(StringRef FilePattern);
981 unsigned readPhdrType();
982 SortSectionPolicy readSortKind();
983 SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
984 SymbolAssignment *readProvideOrAssignment(StringRef Tok);
989 Expr readExpr1(Expr Lhs, int MinPrec);
990 StringRef readParenLiteral();
992 Expr readTernary(Expr Cond);
993 Expr readParenExpr();
995 // For parsing version script.
996 std::vector<SymbolVersion> readVersionExtern();
997 void readAnonymousDeclaration();
998 void readVersionDeclaration(StringRef VerStr);
999 std::vector<SymbolVersion> readSymbols();
1001 ScriptConfiguration &Opt = *ScriptConfig;
1002 bool IsUnderSysroot;
1005 void ScriptParser::readDynamicList() {
1007 readAnonymousDeclaration();
1009 setError("EOF expected, but got " + next());
1012 void ScriptParser::readVersionScript() {
1013 readVersionScriptCommand();
1015 setError("EOF expected, but got " + next());
1018 void ScriptParser::readVersionScriptCommand() {
1020 readAnonymousDeclaration();
1024 while (!atEOF() && !Error && peek() != "}") {
1025 StringRef VerStr = next();
1026 if (VerStr == "{") {
1027 setError("anonymous version definition is used in "
1028 "combination with other version definitions");
1032 readVersionDeclaration(VerStr);
1036 void ScriptParser::readVersion() {
1038 readVersionScriptCommand();
1042 void ScriptParser::readLinkerScript() {
1044 StringRef Tok = next();
1048 if (Tok == "ASSERT") {
1049 Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1050 } else if (Tok == "ENTRY") {
1052 } else if (Tok == "EXTERN") {
1054 } else if (Tok == "GROUP" || Tok == "INPUT") {
1056 } else if (Tok == "INCLUDE") {
1058 } else if (Tok == "OUTPUT") {
1060 } else if (Tok == "OUTPUT_ARCH") {
1062 } else if (Tok == "OUTPUT_FORMAT") {
1064 } else if (Tok == "PHDRS") {
1066 } else if (Tok == "SEARCH_DIR") {
1068 } else if (Tok == "SECTIONS") {
1070 } else if (Tok == "VERSION") {
1072 } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1073 Opt.Commands.emplace_back(Cmd);
1075 setError("unknown directive: " + Tok);
1080 void ScriptParser::addFile(StringRef S) {
1081 if (IsUnderSysroot && S.startswith("/")) {
1082 SmallString<128> PathData;
1083 StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1084 if (sys::fs::exists(Path)) {
1085 Driver->addFile(Saver.save(Path));
1090 if (sys::path::is_absolute(S)) {
1092 } else if (S.startswith("=")) {
1093 if (Config->Sysroot.empty())
1094 Driver->addFile(S.substr(1));
1096 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1097 } else if (S.startswith("-l")) {
1098 Driver->addLibrary(S.substr(2));
1099 } else if (sys::fs::exists(S)) {
1102 if (Optional<std::string> Path = findFromSearchPaths(S))
1103 Driver->addFile(Saver.save(*Path));
1105 setError("unable to find " + S);
1109 void ScriptParser::readAsNeeded() {
1111 bool Orig = Config->AsNeeded;
1112 Config->AsNeeded = true;
1113 while (!Error && !consume(")"))
1114 addFile(unquote(next()));
1115 Config->AsNeeded = Orig;
1118 void ScriptParser::readEntry() {
1119 // -e <symbol> takes predecence over ENTRY(<symbol>).
1121 StringRef Tok = next();
1122 if (Config->Entry.empty())
1123 Config->Entry = Tok;
1127 void ScriptParser::readExtern() {
1129 while (!Error && !consume(")"))
1130 Config->Undefined.push_back(next());
1133 void ScriptParser::readGroup() {
1135 while (!Error && !consume(")")) {
1136 StringRef Tok = next();
1137 if (Tok == "AS_NEEDED")
1140 addFile(unquote(Tok));
1144 void ScriptParser::readInclude() {
1145 StringRef Tok = unquote(next());
1146 // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1147 // The file will be searched for in the current directory, and in any
1148 // directory specified with the -L option.
1149 auto MBOrErr = MemoryBuffer::getFile(Tok);
1151 if (Optional<std::string> Path = findFromSearchPaths(Tok))
1152 MBOrErr = MemoryBuffer::getFile(*Path);
1154 setError("cannot open " + Tok);
1157 MemoryBufferRef MBRef = (*MBOrErr)->getMemBufferRef();
1158 make<std::unique_ptr<MemoryBuffer>>(std::move(*MBOrErr)); // take MB ownership
1162 void ScriptParser::readOutput() {
1163 // -o <file> takes predecence over OUTPUT(<file>).
1165 StringRef Tok = next();
1166 if (Config->OutputFile.empty())
1167 Config->OutputFile = unquote(Tok);
1171 void ScriptParser::readOutputArch() {
1172 // Error checking only for now.
1178 void ScriptParser::readOutputFormat() {
1179 // Error checking only for now.
1182 StringRef Tok = next();
1186 setError("unexpected token: " + Tok);
1195 void ScriptParser::readPhdrs() {
1197 while (!Error && !consume("}")) {
1198 StringRef Tok = next();
1199 Opt.PhdrsCommands.push_back(
1200 {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1201 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1203 PhdrCmd.Type = readPhdrType();
1208 if (Tok == "FILEHDR")
1209 PhdrCmd.HasFilehdr = true;
1210 else if (Tok == "PHDRS")
1211 PhdrCmd.HasPhdrs = true;
1212 else if (Tok == "AT")
1213 PhdrCmd.LMAExpr = readParenExpr();
1214 else if (Tok == "FLAGS") {
1216 // Passing 0 for the value of dot is a bit of a hack. It means that
1217 // we accept expressions like ".|1".
1218 PhdrCmd.Flags = readExpr()(0);
1221 setError("unexpected header attribute: " + Tok);
1226 void ScriptParser::readSearchDir() {
1228 StringRef Tok = next();
1229 if (!Config->Nostdlib)
1230 Config->SearchPaths.push_back(unquote(Tok));
1234 void ScriptParser::readSections() {
1235 Opt.HasSections = true;
1236 // -no-rosegment is used to avoid placing read only non-executable sections in
1237 // their own segment. We do the same if SECTIONS command is present in linker
1238 // script. See comment for computeFlags().
1239 Config->SingleRoRx = true;
1242 while (!Error && !consume("}")) {
1243 StringRef Tok = next();
1244 BaseCommand *Cmd = readProvideOrAssignment(Tok);
1246 if (Tok == "ASSERT")
1247 Cmd = new AssertCommand(readAssert());
1249 Cmd = readOutputSectionDescription(Tok);
1251 Opt.Commands.emplace_back(Cmd);
1255 static int precedence(StringRef Op) {
1256 return StringSwitch<int>(Op)
1259 .Cases("<<", ">>", 3)
1260 .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1265 StringMatcher ScriptParser::readFilePatterns() {
1266 std::vector<StringRef> V;
1267 while (!Error && !consume(")"))
1268 V.push_back(next());
1269 return StringMatcher(V);
1272 SortSectionPolicy ScriptParser::readSortKind() {
1273 if (consume("SORT") || consume("SORT_BY_NAME"))
1274 return SortSectionPolicy::Name;
1275 if (consume("SORT_BY_ALIGNMENT"))
1276 return SortSectionPolicy::Alignment;
1277 if (consume("SORT_BY_INIT_PRIORITY"))
1278 return SortSectionPolicy::Priority;
1279 if (consume("SORT_NONE"))
1280 return SortSectionPolicy::None;
1281 return SortSectionPolicy::Default;
1284 // Method reads a list of sequence of excluded files and section globs given in
1285 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1286 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1287 // The semantics of that is next:
1288 // * Include .foo.1 from every file.
1289 // * Include .foo.2 from every file but a.o
1290 // * Include .foo.3 from every file but b.o
1291 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1292 std::vector<SectionPattern> Ret;
1293 while (!Error && peek() != ")") {
1294 StringMatcher ExcludeFilePat;
1295 if (consume("EXCLUDE_FILE")) {
1297 ExcludeFilePat = readFilePatterns();
1300 std::vector<StringRef> V;
1301 while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1302 V.push_back(next());
1305 Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1307 setError("section pattern is expected");
1312 // Reads contents of "SECTIONS" directive. That directive contains a
1313 // list of glob patterns for input sections. The grammar is as follows.
1315 // <patterns> ::= <section-list>
1316 // | <sort> "(" <section-list> ")"
1317 // | <sort> "(" <sort> "(" <section-list> ")" ")"
1319 // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1320 // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1322 // <section-list> is parsed by readInputSectionsList().
1323 InputSectionDescription *
1324 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1325 auto *Cmd = new InputSectionDescription(FilePattern);
1327 while (!Error && !consume(")")) {
1328 SortSectionPolicy Outer = readSortKind();
1329 SortSectionPolicy Inner = SortSectionPolicy::Default;
1330 std::vector<SectionPattern> V;
1331 if (Outer != SortSectionPolicy::Default) {
1333 Inner = readSortKind();
1334 if (Inner != SortSectionPolicy::Default) {
1336 V = readInputSectionsList();
1339 V = readInputSectionsList();
1343 V = readInputSectionsList();
1346 for (SectionPattern &Pat : V) {
1347 Pat.SortInner = Inner;
1348 Pat.SortOuter = Outer;
1351 std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1356 InputSectionDescription *
1357 ScriptParser::readInputSectionDescription(StringRef Tok) {
1358 // Input section wildcard can be surrounded by KEEP.
1359 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1360 if (Tok == "KEEP") {
1362 StringRef FilePattern = next();
1363 InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1365 Opt.KeptSections.push_back(Cmd);
1368 return readInputSectionRules(Tok);
1371 void ScriptParser::readSort() {
1373 expect("CONSTRUCTORS");
1377 Expr ScriptParser::readAssert() {
1379 Expr E = readExpr();
1381 StringRef Msg = unquote(next());
1383 return [=](uint64_t Dot) {
1384 uint64_t V = E(Dot);
1391 // Reads a FILL(expr) command. We handle the FILL command as an
1392 // alias for =fillexp section attribute, which is different from
1393 // what GNU linkers do.
1394 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1395 uint32_t ScriptParser::readFill() {
1397 uint32_t V = readOutputSectionFiller(next());
1403 OutputSectionCommand *
1404 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1405 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1406 Cmd->Location = getCurrentLocation();
1408 // Read an address expression.
1409 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1411 Cmd->AddrExpr = readExpr();
1416 Cmd->LMAExpr = readParenExpr();
1417 if (consume("ALIGN"))
1418 Cmd->AlignExpr = readParenExpr();
1419 if (consume("SUBALIGN"))
1420 Cmd->SubalignExpr = readParenExpr();
1422 // Parse constraints.
1423 if (consume("ONLY_IF_RO"))
1424 Cmd->Constraint = ConstraintKind::ReadOnly;
1425 if (consume("ONLY_IF_RW"))
1426 Cmd->Constraint = ConstraintKind::ReadWrite;
1429 while (!Error && !consume("}")) {
1430 StringRef Tok = next();
1431 if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
1432 Cmd->Commands.emplace_back(Assignment);
1433 } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
1434 Cmd->Commands.emplace_back(Data);
1435 } else if (Tok == "ASSERT") {
1436 Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1438 } else if (Tok == "FILL") {
1439 Cmd->Filler = readFill();
1440 } else if (Tok == "SORT") {
1442 } else if (peek() == "(") {
1443 Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1445 setError("unknown command " + Tok);
1448 Cmd->Phdrs = readOutputSectionPhdrs();
1451 Cmd->Filler = readOutputSectionFiller(next());
1452 else if (peek().startswith("="))
1453 Cmd->Filler = readOutputSectionFiller(next().drop_front());
1458 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1459 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1461 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1462 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1463 // as 32-bit big-endian values. We will do the same as ld.gold does
1464 // because it's simpler than what ld.bfd does.
1465 uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
1467 if (!Tok.getAsInteger(0, V))
1469 setError("invalid filler expression: " + Tok);
1473 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1475 SymbolAssignment *Cmd = readAssignment(next());
1476 Cmd->Provide = Provide;
1477 Cmd->Hidden = Hidden;
1483 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1484 SymbolAssignment *Cmd = nullptr;
1485 if (peek() == "=" || peek() == "+=") {
1486 Cmd = readAssignment(Tok);
1488 } else if (Tok == "PROVIDE") {
1489 Cmd = readProvideHidden(true, false);
1490 } else if (Tok == "HIDDEN") {
1491 Cmd = readProvideHidden(false, true);
1492 } else if (Tok == "PROVIDE_HIDDEN") {
1493 Cmd = readProvideHidden(true, true);
1498 static uint64_t getSymbolValue(const Twine &Loc, StringRef S, uint64_t Dot) {
1501 return ScriptBase->getSymbolValue(Loc, S);
1504 static bool isAbsolute(StringRef S) {
1507 return ScriptBase->isAbsolute(S);
1510 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1511 StringRef Op = next();
1513 assert(Op == "=" || Op == "+=");
1514 if (consume("ABSOLUTE")) {
1515 // The RHS may be something like "ABSOLUTE(.) & 0xff".
1516 // Call readExpr1 to read the whole expression.
1517 E = readExpr1(readParenExpr(), 0);
1518 E.IsAbsolute = [] { return true; };
1523 std::string Loc = getCurrentLocation();
1524 E = [=](uint64_t Dot) {
1525 return getSymbolValue(Loc, Name, Dot) + E(Dot);
1528 return new SymbolAssignment(Name, E);
1531 // This is an operator-precedence parser to parse a linker
1532 // script expression.
1533 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1535 static Expr combine(StringRef Op, Expr L, Expr R) {
1537 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1539 return [=](uint64_t Dot) -> uint64_t {
1540 uint64_t RHS = R(Dot);
1542 error("division by zero");
1545 return L(Dot) / RHS;
1549 return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1550 [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1552 const OutputSectionBase *S = L.Section();
1553 return S ? S : R.Section();
1556 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1558 return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1560 return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
1562 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1564 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1566 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1568 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
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); };
1577 llvm_unreachable("invalid operator");
1580 // This is a part of the operator-precedence parser. This function
1581 // assumes that the remaining token stream starts with an operator.
1582 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1583 while (!atEOF() && !Error) {
1584 // Read an operator and an expression.
1586 return readTernary(Lhs);
1587 StringRef Op1 = peek();
1588 if (precedence(Op1) < MinPrec)
1591 Expr Rhs = readPrimary();
1593 // Evaluate the remaining part of the expression first if the
1594 // next operator has greater precedence than the previous one.
1595 // For example, if we have read "+" and "3", and if the next
1596 // operator is "*", then we'll evaluate 3 * ... part first.
1598 StringRef Op2 = peek();
1599 if (precedence(Op2) <= precedence(Op1))
1601 Rhs = readExpr1(Rhs, precedence(Op2));
1604 Lhs = combine(Op1, Lhs, Rhs);
1609 uint64_t static getConstant(StringRef S) {
1610 if (S == "COMMONPAGESIZE")
1611 return Target->PageSize;
1612 if (S == "MAXPAGESIZE")
1613 return Config->MaxPageSize;
1614 error("unknown constant: " + S);
1618 // Parses Tok as an integer. Returns true if successful.
1619 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1620 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1621 // "M" (mega) prefixes.
1622 static bool readInteger(StringRef Tok, uint64_t &Result) {
1624 if (Tok.startswith("-")) {
1625 if (!readInteger(Tok.substr(1), Result))
1632 if (Tok.startswith_lower("0x"))
1633 return !Tok.substr(2).getAsInteger(16, Result);
1634 if (Tok.endswith_lower("H"))
1635 return !Tok.drop_back().getAsInteger(16, Result);
1639 if (Tok.endswith_lower("K")) {
1641 Tok = Tok.drop_back();
1642 } else if (Tok.endswith_lower("M")) {
1643 Suffix = 1024 * 1024;
1644 Tok = Tok.drop_back();
1646 if (Tok.getAsInteger(10, Result))
1652 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1653 int Size = StringSwitch<unsigned>(Tok)
1662 return new BytesDataCommand(readParenExpr(), Size);
1665 StringRef ScriptParser::readParenLiteral() {
1667 StringRef Tok = next();
1672 Expr ScriptParser::readPrimary() {
1674 return readParenExpr();
1676 StringRef Tok = next();
1677 std::string Location = getCurrentLocation();
1680 Expr E = readPrimary();
1681 return [=](uint64_t Dot) { return ~E(Dot); };
1684 Expr E = readPrimary();
1685 return [=](uint64_t Dot) { return -E(Dot); };
1688 // Built-in functions are parsed here.
1689 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1690 if (Tok == "ADDR") {
1691 StringRef Name = readParenLiteral();
1692 return {[=](uint64_t Dot) {
1693 return ScriptBase->getOutputSection(Location, Name)->Addr;
1695 [=] { return false; },
1696 [=] { return ScriptBase->getOutputSection(Location, Name); }};
1698 if (Tok == "LOADADDR") {
1699 StringRef Name = readParenLiteral();
1700 return [=](uint64_t Dot) {
1701 return ScriptBase->getOutputSection(Location, Name)->getLMA();
1704 if (Tok == "ASSERT")
1705 return readAssert();
1706 if (Tok == "ALIGN") {
1708 Expr E = readExpr();
1710 Expr E2 = readExpr();
1712 return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
1715 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1717 if (Tok == "CONSTANT") {
1718 StringRef Name = readParenLiteral();
1719 return [=](uint64_t Dot) { return getConstant(Name); };
1721 if (Tok == "DEFINED") {
1722 StringRef Name = readParenLiteral();
1723 return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
1725 if (Tok == "SEGMENT_START") {
1729 Expr E = readExpr();
1731 return [=](uint64_t Dot) { return E(Dot); };
1733 if (Tok == "DATA_SEGMENT_ALIGN") {
1735 Expr E = readExpr();
1739 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1741 if (Tok == "DATA_SEGMENT_END") {
1745 return [](uint64_t Dot) { return Dot; };
1747 // GNU linkers implements more complicated logic to handle
1748 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1749 // the next page boundary for simplicity.
1750 if (Tok == "DATA_SEGMENT_RELRO_END") {
1756 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1758 if (Tok == "SIZEOF") {
1759 StringRef Name = readParenLiteral();
1760 return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1762 if (Tok == "ALIGNOF") {
1763 StringRef Name = readParenLiteral();
1764 return [=](uint64_t Dot) {
1765 return ScriptBase->getOutputSection(Location, Name)->Addralign;
1768 if (Tok == "SIZEOF_HEADERS")
1769 return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1771 // Tok is a literal number.
1773 if (readInteger(Tok, V))
1774 return [=](uint64_t Dot) { return V; };
1776 // Tok is a symbol name.
1777 if (Tok != "." && !isValidCIdentifier(Tok))
1778 setError("malformed number: " + Tok);
1779 return {[=](uint64_t Dot) { return getSymbolValue(Location, Tok, Dot); },
1780 [=] { return isAbsolute(Tok); },
1781 [=] { return ScriptBase->getSymbolSection(Tok); }};
1784 Expr ScriptParser::readTernary(Expr Cond) {
1785 Expr L = readExpr();
1787 Expr R = readExpr();
1788 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1791 Expr ScriptParser::readParenExpr() {
1793 Expr E = readExpr();
1798 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1799 std::vector<StringRef> Phdrs;
1800 while (!Error && peek().startswith(":")) {
1801 StringRef Tok = next();
1802 Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1807 // Read a program header type name. The next token must be a
1808 // name of a program header type or a constant (e.g. "0x3").
1809 unsigned ScriptParser::readPhdrType() {
1810 StringRef Tok = next();
1812 if (readInteger(Tok, Val))
1815 unsigned Ret = StringSwitch<unsigned>(Tok)
1816 .Case("PT_NULL", PT_NULL)
1817 .Case("PT_LOAD", PT_LOAD)
1818 .Case("PT_DYNAMIC", PT_DYNAMIC)
1819 .Case("PT_INTERP", PT_INTERP)
1820 .Case("PT_NOTE", PT_NOTE)
1821 .Case("PT_SHLIB", PT_SHLIB)
1822 .Case("PT_PHDR", PT_PHDR)
1823 .Case("PT_TLS", PT_TLS)
1824 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1825 .Case("PT_GNU_STACK", PT_GNU_STACK)
1826 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1827 .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1828 .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1829 .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1832 if (Ret == (unsigned)-1) {
1833 setError("invalid program header type: " + Tok);
1839 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1840 void ScriptParser::readAnonymousDeclaration() {
1841 // Read global symbols first. "global:" is default, so if there's
1842 // no label, we assume global symbols.
1843 if (consume("global:") || peek() != "local:")
1844 Config->VersionScriptGlobals = readSymbols();
1846 // Next, read local symbols.
1847 if (consume("local:")) {
1849 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1852 setError("local symbol list for anonymous version is not supported");
1859 // Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
1860 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1861 // Identifiers start at 2 because 0 and 1 are reserved
1862 // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1863 uint16_t VersionId = Config->VersionDefinitions.size() + 2;
1864 Config->VersionDefinitions.push_back({VerStr, VersionId});
1866 // Read global symbols.
1867 if (consume("global:") || peek() != "local:")
1868 Config->VersionDefinitions.back().Globals = readSymbols();
1870 // Read local symbols.
1871 if (consume("local:")) {
1873 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1876 for (SymbolVersion V : readSymbols())
1877 Config->VersionScriptLocals.push_back(V);
1882 // Each version may have a parent version. For example, "Ver2"
1883 // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1884 // as a parent. This version hierarchy is, probably against your
1885 // instinct, purely for hint; the runtime doesn't care about it
1886 // at all. In LLD, we simply ignore it.
1892 // Reads a list of symbols for a versions cript.
1893 std::vector<SymbolVersion> ScriptParser::readSymbols() {
1894 std::vector<SymbolVersion> Ret;
1896 if (consume("extern")) {
1897 for (SymbolVersion V : readVersionExtern())
1902 if (peek() == "}" || peek() == "local:" || Error)
1904 StringRef Tok = next();
1905 Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
1911 // Reads an "extern C++" directive, e.g.,
1912 // "extern "C++" { ns::*; "f(int, double)"; };"
1913 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1914 StringRef Tok = next();
1915 bool IsCXX = Tok == "\"C++\"";
1916 if (!IsCXX && Tok != "\"C\"")
1917 setError("Unknown language");
1920 std::vector<SymbolVersion> Ret;
1921 while (!Error && peek() != "}") {
1922 StringRef Tok = next();
1923 bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1924 Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1933 void elf::readLinkerScript(MemoryBufferRef MB) {
1934 ScriptParser(MB).readLinkerScript();
1937 void elf::readVersionScript(MemoryBufferRef MB) {
1938 ScriptParser(MB).readVersionScript();
1941 void elf::readDynamicList(MemoryBufferRef MB) {
1942 ScriptParser(MB).readDynamicList();
1945 template class elf::LinkerScript<ELF32LE>;
1946 template class elf::LinkerScript<ELF32BE>;
1947 template class elf::LinkerScript<ELF64LE>;
1948 template class elf::LinkerScript<ELF64BE>;