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"
16 #include "InputSection.h"
18 #include "OutputSections.h"
20 #include "SymbolTable.h"
22 #include "SyntheticSections.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Support/Endian.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
44 using namespace llvm::ELF;
45 using namespace llvm::object;
46 using namespace llvm::support::endian;
48 using namespace lld::elf;
50 LinkerScript *elf::Script;
52 uint64_t ExprValue::getValue() const {
54 if (Sec->getOutputSection())
55 return alignTo(Sec->getOffset(Val) + Sec->getOutputSection()->Addr,
57 error("unable to evaluate expression: input section " + Sec->Name +
58 " has no output section assigned");
60 return alignTo(Val, Alignment);
63 uint64_t ExprValue::getSecAddr() const {
65 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
69 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
71 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
72 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
73 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
75 Sym->Binding = STB_GLOBAL;
76 ExprValue Value = Cmd->Expression();
77 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
79 // We want to set symbol values early if we can. This allows us to use symbols
80 // as variables in linker scripts. Doing so allows us to write expressions
81 // like this: `alignment = 16; . = ALIGN(., alignment)`
82 uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
83 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
84 STT_NOTYPE, SymValue, 0, Sec, nullptr);
88 OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
90 for (OutputSection *Sec : *OutputSections)
91 if (Sec->Name == Name)
94 static OutputSection Dummy("", 0, 0);
95 if (ErrorOnMissingSection)
96 error(Loc + ": undefined section " + Name);
100 // This function is essentially the same as getOutputSection(Name)->Size,
101 // but it won't print out an error message if a given section is not found.
103 // Linker script does not create an output section if its content is empty.
104 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
105 // be empty. That is why this function is different from getOutputSection().
106 uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
107 for (OutputSection *Sec : *OutputSections)
108 if (Sec->Name == Name)
113 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
114 uint64_t Val = E().getValue();
117 error(Loc + ": unable to move location counter backward for: " +
120 error(Loc + ": unable to move location counter backward");
123 // Update to location counter means update to section size.
125 CurOutSec->Size = Dot - CurOutSec->Addr;
128 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
129 // symbols, whose value is an offset from beginning of section and regular
130 // symbols whose value is absolute.
131 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
132 if (Cmd->Name == ".") {
133 setDot(Cmd->Expression, Cmd->Location, InSec);
140 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
141 ExprValue V = Cmd->Expression();
142 if (V.isAbsolute()) {
143 Sym->Value = V.getValue();
145 Sym->Section = V.Sec;
146 if (Sym->Section->Flags & SHF_ALLOC)
147 Sym->Value = alignTo(V.Val, V.Alignment);
149 Sym->Value = V.getValue();
153 static SymbolBody *findSymbol(StringRef S) {
154 switch (Config->EKind) {
156 return Symtab<ELF32LE>::X->find(S);
158 return Symtab<ELF32BE>::X->find(S);
160 return Symtab<ELF64LE>::X->find(S);
162 return Symtab<ELF64BE>::X->find(S);
164 llvm_unreachable("unknown Config->EKind");
168 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
169 switch (Config->EKind) {
171 return addRegular<ELF32LE>(Cmd);
173 return addRegular<ELF32BE>(Cmd);
175 return addRegular<ELF64LE>(Cmd);
177 return addRegular<ELF64BE>(Cmd);
179 llvm_unreachable("unknown Config->EKind");
183 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
184 if (Cmd->Name == ".")
187 // If a symbol was in PROVIDE(), we need to define it only when
188 // it is a referenced undefined symbol.
189 SymbolBody *B = findSymbol(Cmd->Name);
190 if (Cmd->Provide && (!B || B->isDefined()))
193 Cmd->Sym = addRegularSymbol(Cmd);
196 bool SymbolAssignment::classof(const BaseCommand *C) {
197 return C->Kind == AssignmentKind;
200 bool OutputSectionCommand::classof(const BaseCommand *C) {
201 return C->Kind == OutputSectionKind;
204 // Fill [Buf, Buf + Size) with Filler.
205 // This is used for linker script "=fillexp" command.
206 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
208 for (; I + 4 < Size; I += 4)
209 memcpy(Buf + I, &Filler, 4);
210 memcpy(Buf + I, &Filler, Size - I);
213 bool InputSectionDescription::classof(const BaseCommand *C) {
214 return C->Kind == InputSectionKind;
217 bool AssertCommand::classof(const BaseCommand *C) {
218 return C->Kind == AssertKind;
221 bool BytesDataCommand::classof(const BaseCommand *C) {
222 return C->Kind == BytesDataKind;
225 static StringRef basename(InputSectionBase *S) {
227 return sys::path::filename(S->File->getName());
231 bool LinkerScript::shouldKeep(InputSectionBase *S) {
232 for (InputSectionDescription *ID : Opt.KeptSections)
233 if (ID->FilePat.match(basename(S)))
234 for (SectionPattern &P : ID->SectionPatterns)
235 if (P.SectionPat.match(S->Name))
240 // A helper function for the SORT() command.
241 static std::function<bool(InputSectionBase *, InputSectionBase *)>
242 getComparator(SortSectionPolicy K) {
244 case SortSectionPolicy::Alignment:
245 return [](InputSectionBase *A, InputSectionBase *B) {
246 // ">" is not a mistake. Sections with larger alignments are placed
247 // before sections with smaller alignments in order to reduce the
248 // amount of padding necessary. This is compatible with GNU.
249 return A->Alignment > B->Alignment;
251 case SortSectionPolicy::Name:
252 return [](InputSectionBase *A, InputSectionBase *B) {
253 return A->Name < B->Name;
255 case SortSectionPolicy::Priority:
256 return [](InputSectionBase *A, InputSectionBase *B) {
257 return getPriority(A->Name) < getPriority(B->Name);
260 llvm_unreachable("unknown sort policy");
264 // A helper function for the SORT() command.
265 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
266 ConstraintKind Kind) {
267 if (Kind == ConstraintKind::NoConstraint)
270 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
271 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
274 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
275 (!IsRW && Kind == ConstraintKind::ReadOnly);
278 static void sortSections(InputSection **Begin, InputSection **End,
279 SortSectionPolicy K) {
280 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
281 std::stable_sort(Begin, End, getComparator(K));
284 // Compute and remember which sections the InputSectionDescription matches.
285 std::vector<InputSection *>
286 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
287 std::vector<InputSection *> Ret;
289 // Collects all sections that satisfy constraints of Cmd.
290 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
291 size_t SizeBefore = Ret.size();
293 for (InputSectionBase *Sec : InputSections) {
294 if (!isa<InputSection>(Sec))
300 // For -emit-relocs we have to ignore entries like
301 // .rela.dyn : { *(.rela.data) }
302 // which are common because they are in the default bfd script.
303 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
306 StringRef Filename = basename(Sec);
307 if (!Cmd->FilePat.match(Filename) ||
308 Pat.ExcludedFilePat.match(Filename) ||
309 !Pat.SectionPat.match(Sec->Name))
312 Ret.push_back(cast<InputSection>(Sec));
313 Sec->Assigned = true;
316 // Sort sections as instructed by SORT-family commands and --sort-section
317 // option. Because SORT-family commands can be nested at most two depth
318 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
319 // line option is respected even if a SORT command is given, the exact
320 // behavior we have here is a bit complicated. Here are the rules.
322 // 1. If two SORT commands are given, --sort-section is ignored.
323 // 2. If one SORT command is given, and if it is not SORT_NONE,
324 // --sort-section is handled as an inner SORT command.
325 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
326 // 4. If no SORT command is given, sort according to --sort-section.
327 InputSection **Begin = Ret.data() + SizeBefore;
328 InputSection **End = Ret.data() + Ret.size();
329 if (Pat.SortOuter != SortSectionPolicy::None) {
330 if (Pat.SortInner == SortSectionPolicy::Default)
331 sortSections(Begin, End, Config->SortSection);
333 sortSections(Begin, End, Pat.SortInner);
334 sortSections(Begin, End, Pat.SortOuter);
340 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
341 for (InputSectionBase *S : V) {
343 if (S == InX::ShStrTab)
344 error("discarding .shstrtab section is not allowed");
345 discard(S->DependentSections);
349 std::vector<InputSectionBase *>
350 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
351 std::vector<InputSectionBase *> Ret;
353 for (BaseCommand *Base : OutCmd.Commands) {
354 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
358 Cmd->Sections = computeInputSections(Cmd);
359 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
365 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
366 // A symbol can be assigned before any section is mentioned in the linker
367 // script. In an DSO, the symbol values are addresses, so the only important
368 // section values are:
371 // * Any value meaning a regular section.
372 // To handle that, create a dummy aether section that fills the void before
373 // the linker scripts switches to another section. It has an index of one
374 // which will map to whatever the first actual section is.
375 Aether = make<OutputSection>("", 0, SHF_ALLOC);
376 Aether->SectionIndex = 1;
380 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
381 // Handle symbol assignments outside of any output section.
382 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
387 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
388 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
390 // The output section name `/DISCARD/' is special.
391 // Any input section assigned to it is discarded.
392 if (Cmd->Name == "/DISCARD/") {
397 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
398 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
399 // sections satisfy a given constraint. If not, a directive is handled
400 // as if it wasn't present from the beginning.
402 // Because we'll iterate over Commands many more times, the easiest
403 // way to "make it as if it wasn't present" is to just remove it.
404 if (!matchConstraints(V, Cmd->Constraint)) {
405 for (InputSectionBase *S : V)
407 Opt.Commands.erase(Opt.Commands.begin() + I);
412 // A directive may contain symbol definitions like this:
413 // ".foo : { ...; bar = .; }". Handle them.
414 for (BaseCommand *Base : Cmd->Commands)
415 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
418 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
419 // is given, input sections are aligned to that value, whether the
420 // given value is larger or smaller than the original section alignment.
421 if (Cmd->SubalignExpr) {
422 uint32_t Subalign = Cmd->SubalignExpr().getValue();
423 for (InputSectionBase *S : V)
424 S->Alignment = Subalign;
427 // Add input sections to an output section.
428 for (InputSectionBase *S : V)
429 Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
430 if (OutputSection *Sec = Cmd->Sec) {
431 assert(Sec->SectionIndex == INT_MAX);
432 Sec->SectionIndex = I;
433 SecToCommand[Sec] = Cmd;
440 void LinkerScript::fabricateDefaultCommands() {
441 std::vector<BaseCommand *> Commands;
443 // Define start address
444 uint64_t StartAddr = Config->ImageBase + elf::getHeaderSize();
446 // The Sections with -T<section> have been sorted in order of ascending
447 // address. We must lower StartAddr if the lowest -T<section address> as
448 // calls to setDot() must be monotonically increasing.
449 for (auto& KV : Config->SectionStartMap)
450 StartAddr = std::min(StartAddr, KV.second);
453 make<SymbolAssignment>(".", [=] { return StartAddr; }, ""));
455 // For each OutputSection that needs a VA fabricate an OutputSectionCommand
456 // with an InputSectionDescription describing the InputSections
457 for (OutputSection *Sec : *OutputSections) {
458 auto *OSCmd = make<OutputSectionCommand>(Sec->Name);
460 SecToCommand[Sec] = OSCmd;
462 // Prefer user supplied address over additional alignment constraint
463 auto I = Config->SectionStartMap.find(Sec->Name);
464 if (I != Config->SectionStartMap.end())
466 make<SymbolAssignment>(".", [=] { return I->second; }, ""));
467 else if (Sec->PageAlign)
468 OSCmd->AddrExpr = [=] {
469 return alignTo(Script->getDot(), Config->MaxPageSize);
472 Commands.push_back(OSCmd);
473 if (Sec->Sections.size()) {
474 auto *ISD = make<InputSectionDescription>("");
475 OSCmd->Commands.push_back(ISD);
476 for (InputSection *ISec : Sec->Sections) {
477 ISD->Sections.push_back(ISec);
478 ISec->Assigned = true;
482 // SECTIONS commands run before other non SECTIONS commands
483 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
484 Opt.Commands = std::move(Commands);
487 // Add sections that didn't match any sections command.
488 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
489 for (InputSectionBase *S : InputSections) {
490 if (!S->Live || S->OutSec)
492 StringRef Name = getOutputSectionName(S->Name);
493 auto I = std::find_if(
494 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
495 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
496 return Cmd->Name == Name;
499 if (I == Opt.Commands.end()) {
500 Factory.addInputSec(S, Name);
502 auto *Cmd = cast<OutputSectionCommand>(*I);
503 Factory.addInputSec(S, Name, Cmd->Sec);
504 if (OutputSection *Sec = Cmd->Sec) {
505 SecToCommand[Sec] = Cmd;
506 unsigned Index = std::distance(Opt.Commands.begin(), I);
507 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
508 Sec->SectionIndex = Index;
510 auto *ISD = make<InputSectionDescription>("");
511 ISD->Sections.push_back(cast<InputSection>(S));
512 Cmd->Commands.push_back(ISD);
517 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
518 bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
519 uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
520 Start = alignTo(Start, Align);
521 uint64_t End = Start + Size;
524 ThreadBssOffset = End - Dot;
530 void LinkerScript::output(InputSection *S) {
531 uint64_t Pos = advance(S->getSize(), S->Alignment);
532 S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
534 // Update output section size after adding each section. This is so that
535 // SIZEOF works correctly in the case below:
536 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
537 CurOutSec->Size = Pos - CurOutSec->Addr;
539 // If there is a memory region associated with this input section, then
540 // place the section in that region and update the region index.
542 CurMemRegion->Offset += CurOutSec->Size;
543 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
544 if (CurSize > CurMemRegion->Length) {
545 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
546 error("section '" + CurOutSec->Name + "' will not fit in region '" +
547 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
553 void LinkerScript::switchTo(OutputSection *Sec) {
554 if (CurOutSec == Sec)
558 CurOutSec->Addr = advance(0, CurOutSec->Alignment);
560 // If neither AT nor AT> is specified for an allocatable section, the linker
561 // will set the LMA such that the difference between VMA and LMA for the
562 // section is the same as the preceding output section in the same region
563 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
565 CurOutSec->LMAOffset = LMAOffset();
568 void LinkerScript::process(BaseCommand &Base) {
569 // This handles the assignments to symbol or to the dot.
570 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
571 assignSymbol(Cmd, true);
575 // Handle BYTE(), SHORT(), LONG(), or QUAD().
576 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
577 Cmd->Offset = Dot - CurOutSec->Addr;
579 CurOutSec->Size = Dot - CurOutSec->Addr;
584 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
589 // Handle a single input section description command.
590 // It calculates and assigns the offsets for each section and also
591 // updates the output section size.
592 auto &Cmd = cast<InputSectionDescription>(Base);
593 for (InputSectionBase *Sec : Cmd.Sections) {
594 // We tentatively added all synthetic sections at the beginning and removed
595 // empty ones afterwards (because there is no way to know whether they were
596 // going be empty or not other than actually running linker scripts.)
597 // We need to ignore remains of empty sections.
598 if (auto *S = dyn_cast<SyntheticSection>(Sec))
604 assert(CurOutSec == Sec->OutSec);
605 output(cast<InputSection>(Sec));
609 // This function searches for a memory region to place the given output
610 // section in. If found, a pointer to the appropriate memory region is
611 // returned. Otherwise, a nullptr is returned.
612 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
613 // If a memory region name was specified in the output section command,
614 // then try to find that region first.
615 if (!Cmd->MemoryRegionName.empty()) {
616 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
617 if (It != Opt.MemoryRegions.end())
619 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
623 // If at least one memory region is defined, all sections must
624 // belong to some memory region. Otherwise, we don't need to do
625 // anything for memory regions.
626 if (Opt.MemoryRegions.empty())
629 OutputSection *Sec = Cmd->Sec;
630 // See if a region can be found by matching section flags.
631 for (auto &Pair : Opt.MemoryRegions) {
632 MemoryRegion &M = Pair.second;
633 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
637 // Otherwise, no suitable region was found.
638 if (Sec->Flags & SHF_ALLOC)
639 error("no memory region specified for section '" + Sec->Name + "'");
643 // This function assigns offsets to input sections and an output section
644 // for a single sections command (e.g. ".text { *(.text); }").
645 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
646 OutputSection *Sec = Cmd->Sec;
650 if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
651 setDot(Cmd->AddrExpr, Cmd->Location, false);
655 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
658 CurMemRegion = Cmd->MemRegion;
660 Dot = CurMemRegion->Offset;
663 // We do not support custom layout for compressed debug sectons.
664 // At this point we already know their size and have compressed content.
665 if (CurOutSec->Flags & SHF_COMPRESSED)
668 for (BaseCommand *C : Cmd->Commands)
672 void LinkerScript::removeEmptyCommands() {
673 // It is common practice to use very generic linker scripts. So for any
674 // given run some of the output sections in the script will be empty.
675 // We could create corresponding empty output sections, but that would
676 // clutter the output.
677 // We instead remove trivially empty sections. The bfd linker seems even
678 // more aggressive at removing them.
679 auto Pos = std::remove_if(
680 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
681 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
682 return std::find(OutputSections->begin(), OutputSections->end(),
683 Cmd->Sec) == OutputSections->end();
686 Opt.Commands.erase(Pos, Opt.Commands.end());
689 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
690 for (BaseCommand *Base : Cmd.Commands)
691 if (!isa<InputSectionDescription>(*Base))
696 void LinkerScript::adjustSectionsBeforeSorting() {
697 // If the output section contains only symbol assignments, create a
698 // corresponding output section. The bfd linker seems to only create them if
699 // '.' is assigned to, but creating these section should not have any bad
700 // consequeces and gives us a section to put the symbol in.
701 uint64_t Flags = SHF_ALLOC;
703 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
704 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
707 if (OutputSection *Sec = Cmd->Sec) {
712 if (isAllSectionDescription(*Cmd))
715 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
716 OutSec->SectionIndex = I;
717 OutputSections->push_back(OutSec);
719 SecToCommand[OutSec] = Cmd;
723 void LinkerScript::adjustSectionsAfterSorting() {
724 placeOrphanSections();
726 // Try and find an appropriate memory region to assign offsets in.
727 for (BaseCommand *Base : Opt.Commands) {
728 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
729 Cmd->MemRegion = findMemoryRegion(Cmd);
730 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
732 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
736 // If output section command doesn't specify any segments,
737 // and we haven't previously assigned any section to segment,
738 // then we simply assign section to the very first load segment.
739 // Below is an example of such linker script:
740 // PHDRS { seg PT_LOAD; }
741 // SECTIONS { .aaa : { *(.aaa) } }
742 std::vector<StringRef> DefPhdrs;
744 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
745 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
746 if (FirstPtLoad != Opt.PhdrsCommands.end())
747 DefPhdrs.push_back(FirstPtLoad->Name);
749 // Walk the commands and propagate the program headers to commands that don't
750 // explicitly specify them.
751 for (BaseCommand *Base : Opt.Commands) {
752 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
756 if (Cmd->Phdrs.empty())
757 Cmd->Phdrs = DefPhdrs;
759 DefPhdrs = Cmd->Phdrs;
762 removeEmptyCommands();
765 // When placing orphan sections, we want to place them after symbol assignments
766 // so that an orphan after
770 // doesn't break the intended meaning of the begin/end symbols.
771 // We don't want to go over sections since Writer<ELFT>::sortSections is the
772 // one in charge of deciding the order of the sections.
773 // We don't want to go over alignments, since doing so in
774 // rx_sec : { *(rx_sec) }
775 // . = ALIGN(0x1000);
776 // /* The RW PT_LOAD starts here*/
777 // rw_sec : { *(rw_sec) }
778 // would mean that the RW PT_LOAD would become unaligned.
779 static bool shouldSkip(BaseCommand *Cmd) {
780 if (isa<OutputSectionCommand>(Cmd))
782 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
783 return Assign->Name != ".";
787 // Orphan sections are sections present in the input files which are
788 // not explicitly placed into the output file by the linker script.
790 // When the control reaches this function, Opt.Commands contains
791 // output section commands for non-orphan sections only. This function
792 // adds new elements for orphan sections so that all sections are
793 // explicitly handled by Opt.Commands.
795 // Writer<ELFT>::sortSections has already sorted output sections.
796 // What we need to do is to scan OutputSections vector and
797 // Opt.Commands in parallel to find orphan sections. If there is an
798 // output section that doesn't have a corresponding entry in
799 // Opt.Commands, we will insert a new entry to Opt.Commands.
801 // There is some ambiguity as to where exactly a new entry should be
802 // inserted, because Opt.Commands contains not only output section
803 // commands but also other types of commands such as symbol assignment
804 // expressions. There's no correct answer here due to the lack of the
805 // formal specification of the linker script. We use heuristics to
806 // determine whether a new output command should be added before or
807 // after another commands. For the details, look at shouldSkip
809 void LinkerScript::placeOrphanSections() {
810 // The OutputSections are already in the correct order.
811 // This loops creates or moves commands as needed so that they are in the
815 // As a horrible special case, skip the first . assignment if it is before any
816 // section. We do this because it is common to set a load address by starting
817 // the script with ". = 0xabcd" and the expectation is that every section is
819 auto FirstSectionOrDotAssignment =
820 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
821 [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
822 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
823 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
824 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
828 for (OutputSection *Sec : *OutputSections) {
829 StringRef Name = Sec->Name;
831 // Find the last spot where we can insert a command and still get the
833 auto CmdIter = Opt.Commands.begin() + CmdIndex;
834 auto E = Opt.Commands.end();
835 while (CmdIter != E && shouldSkip(*CmdIter)) {
840 // If there is no command corresponding to this output section,
841 // create one and put a InputSectionDescription in it so that both
842 // representations agree on which input sections to use.
843 OutputSectionCommand *Cmd = getCmd(Sec);
845 Cmd = make<OutputSectionCommand>(Name);
846 Opt.Commands.insert(CmdIter, Cmd);
850 SecToCommand[Sec] = Cmd;
851 auto *ISD = make<InputSectionDescription>("");
852 for (InputSection *IS : Sec->Sections)
853 ISD->Sections.push_back(IS);
854 Cmd->Commands.push_back(ISD);
859 // Continue from where we found it.
860 while (*CmdIter != Cmd) {
868 void LinkerScript::processNonSectionCommands() {
869 for (BaseCommand *Base : Opt.Commands) {
870 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
871 assignSymbol(Cmd, false);
872 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
877 // Do a last effort at synchronizing the linker script "AST" and the section
878 // list. This is needed to account for last minute changes, like adding a
879 // .ARM.exidx terminator and sorting SHF_LINK_ORDER sections.
881 // FIXME: We should instead create the "AST" earlier and the above changes would
882 // be done directly in the "AST".
884 // This can only handle new sections being added and sections being reordered.
885 void LinkerScript::synchronize() {
886 for (BaseCommand *Base : Opt.Commands) {
887 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
890 ArrayRef<InputSection *> Sections = Cmd->Sec->Sections;
891 std::vector<InputSection **> ScriptSections;
892 DenseSet<InputSection *> ScriptSectionsSet;
893 for (BaseCommand *Base : Cmd->Commands) {
894 auto *ISD = dyn_cast<InputSectionDescription>(Base);
897 for (InputSection *&IS : ISD->Sections) {
899 ScriptSections.push_back(&IS);
900 ScriptSectionsSet.insert(IS);
904 std::vector<InputSection *> Missing;
905 for (InputSection *IS : Sections)
906 if (!ScriptSectionsSet.count(IS))
907 Missing.push_back(IS);
908 if (!Missing.empty()) {
909 auto ISD = make<InputSectionDescription>("");
910 ISD->Sections = Missing;
911 Cmd->Commands.push_back(ISD);
912 for (InputSection *&IS : ISD->Sections)
914 ScriptSections.push_back(&IS);
916 assert(ScriptSections.size() == Sections.size());
917 for (int I = 0, N = Sections.size(); I < N; ++I)
918 *ScriptSections[I] = Sections[I];
922 static bool allocateHeaders(std::vector<PhdrEntry> &Phdrs,
923 ArrayRef<OutputSection *> OutputSections,
926 std::find_if(Phdrs.begin(), Phdrs.end(),
927 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
928 if (FirstPTLoad == Phdrs.end())
931 uint64_t HeaderSize = getHeaderSize();
932 if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
933 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
934 Out::ElfHeader->Addr = Min;
935 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
939 assert(FirstPTLoad->First == Out::ElfHeader);
940 OutputSection *ActualFirst = nullptr;
941 for (OutputSection *Sec : OutputSections) {
942 if (Sec->FirstInPtLoad == Out::ElfHeader) {
948 for (OutputSection *Sec : OutputSections)
949 if (Sec->FirstInPtLoad == Out::ElfHeader)
950 Sec->FirstInPtLoad = ActualFirst;
951 FirstPTLoad->First = ActualFirst;
953 Phdrs.erase(FirstPTLoad);
956 auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
957 return E.p_type == PT_PHDR;
959 if (PhdrI != Phdrs.end())
964 void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
965 // Assign addresses as instructed by linker script SECTIONS sub-commands.
967 ErrorOnMissingSection = true;
970 for (BaseCommand *Base : Opt.Commands) {
971 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
972 assignSymbol(Cmd, false);
976 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
981 auto *Cmd = cast<OutputSectionCommand>(Base);
985 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
986 for (OutputSection *Sec : *OutputSections) {
987 if (Sec->Flags & SHF_ALLOC)
988 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
993 allocateHeaders(Phdrs, *OutputSections, MinVA);
996 // Creates program headers as instructed by PHDRS linker script command.
997 std::vector<PhdrEntry> LinkerScript::createPhdrs() {
998 std::vector<PhdrEntry> Ret;
1000 // Process PHDRS and FILEHDR keywords because they are not
1001 // real output sections and cannot be added in the following loop.
1002 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1003 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
1004 PhdrEntry &Phdr = Ret.back();
1007 Phdr.add(Out::ElfHeader);
1009 Phdr.add(Out::ProgramHeaders);
1012 Phdr.p_paddr = Cmd.LMAExpr().getValue();
1017 // Add output sections to program headers.
1018 for (OutputSection *Sec : *OutputSections) {
1019 if (!(Sec->Flags & SHF_ALLOC))
1022 // Assign headers specified by linker script
1023 for (size_t Id : getPhdrIndices(Sec)) {
1025 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
1026 Ret[Id].p_flags |= Sec->getPhdrFlags();
1032 bool LinkerScript::ignoreInterpSection() {
1033 // Ignore .interp section in case we have PHDRS specification
1034 // and PT_INTERP isn't listed.
1035 if (Opt.PhdrsCommands.empty())
1037 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
1038 if (Cmd.Type == PT_INTERP)
1043 OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
1044 auto I = SecToCommand.find(Sec);
1045 if (I == SecToCommand.end())
1050 uint32_t OutputSectionCommand::getFiller() {
1053 if (Sec->Flags & SHF_EXECINSTR)
1054 return Target->TrapInstr;
1058 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
1062 write16(Buf, Data, Config->Endianness);
1064 write32(Buf, Data, Config->Endianness);
1066 write64(Buf, Data, Config->Endianness);
1068 llvm_unreachable("unsupported Size argument");
1071 template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
1074 // We may have already rendered compressed content when using
1075 // -compress-debug-sections option. Write it together with header.
1076 if (!Sec->CompressedData.empty()) {
1077 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1078 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1079 Sec->CompressedData.size());
1083 if (Sec->Type == SHT_NOBITS)
1086 // Write leading padding.
1087 ArrayRef<InputSection *> Sections = Sec->Sections;
1088 uint32_t Filler = getFiller();
1090 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1092 parallelForEachN(0, Sections.size(), [=](size_t I) {
1093 InputSection *IS = Sections[I];
1094 IS->writeTo<ELFT>(Buf);
1096 // Fill gaps between sections.
1098 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1100 if (I + 1 == Sections.size())
1101 End = Buf + Sec->Size;
1103 End = Buf + Sections[I + 1]->OutSecOff;
1104 fill(Start, End - Start, Filler);
1108 // Linker scripts may have BYTE()-family commands with which you
1109 // can write arbitrary bytes to the output. Process them if any.
1110 for (BaseCommand *Base : Commands)
1111 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1112 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
1115 bool LinkerScript::hasLMA(OutputSection *Sec) {
1116 if (OutputSectionCommand *Cmd = getCmd(Sec))
1122 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
1124 return {CurOutSec, Dot - CurOutSec->Addr};
1125 if (SymbolBody *B = findSymbol(S)) {
1126 if (auto *D = dyn_cast<DefinedRegular>(B))
1127 return {D->Section, D->Value};
1128 if (auto *C = dyn_cast<DefinedCommon>(B))
1129 return {InX::Common, C->Offset};
1131 error(Loc + ": symbol not found: " + S);
1135 bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
1137 // Returns indices of ELF headers containing specific section. Each index is a
1138 // zero based number of ELF header listed within PHDRS {} script block.
1139 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) {
1140 if (OutputSectionCommand *Cmd = getCmd(Sec)) {
1141 std::vector<size_t> Ret;
1142 for (StringRef PhdrName : Cmd->Phdrs)
1143 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
1149 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1151 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1152 if (Cmd.Name == PhdrName)
1156 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1160 template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1161 template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1162 template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1163 template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);