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/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
45 using namespace llvm::ELF;
46 using namespace llvm::object;
47 using namespace llvm::support::endian;
49 using namespace lld::elf;
51 LinkerScript *elf::Script;
53 uint64_t ExprValue::getValue() const {
55 if (OutputSection *OS = Sec->getOutputSection())
56 return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
57 error(Loc + ": 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 OutputSectionCommand *
89 LinkerScript::createOutputSectionCommand(StringRef Name, StringRef Location) {
90 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
91 OutputSectionCommand *Cmd;
92 if (CmdRef && CmdRef->Location.empty()) {
93 // There was a forward reference.
96 Cmd = make<OutputSectionCommand>(Name);
100 Cmd->Location = Location;
104 OutputSectionCommand *
105 LinkerScript::getOrCreateOutputSectionCommand(StringRef Name) {
106 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
108 CmdRef = make<OutputSectionCommand>(Name);
112 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
113 uint64_t Val = E().getValue();
116 error(Loc + ": unable to move location counter backward for: " +
119 error(Loc + ": unable to move location counter backward");
122 // Update to location counter means update to section size.
124 CurOutSec->Size = Dot - CurOutSec->Addr;
127 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
128 // symbols, whose value is an offset from beginning of section and regular
129 // symbols whose value is absolute.
130 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
131 if (Cmd->Name == ".") {
132 setDot(Cmd->Expression, Cmd->Location, InSec);
139 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
140 ExprValue V = Cmd->Expression();
141 if (V.isAbsolute()) {
142 Sym->Value = V.getValue();
144 Sym->Section = V.Sec;
145 if (Sym->Section->Flags & SHF_ALLOC)
146 Sym->Value = alignTo(V.Val, V.Alignment);
148 Sym->Value = V.getValue();
152 static SymbolBody *findSymbol(StringRef S) {
153 switch (Config->EKind) {
155 return Symtab<ELF32LE>::X->find(S);
157 return Symtab<ELF32BE>::X->find(S);
159 return Symtab<ELF64LE>::X->find(S);
161 return Symtab<ELF64BE>::X->find(S);
163 llvm_unreachable("unknown Config->EKind");
167 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
168 switch (Config->EKind) {
170 return addRegular<ELF32LE>(Cmd);
172 return addRegular<ELF32BE>(Cmd);
174 return addRegular<ELF64LE>(Cmd);
176 return addRegular<ELF64BE>(Cmd);
178 llvm_unreachable("unknown Config->EKind");
182 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
183 if (Cmd->Name == ".")
186 // If a symbol was in PROVIDE(), we need to define it only when
187 // it is a referenced undefined symbol.
188 SymbolBody *B = findSymbol(Cmd->Name);
189 if (Cmd->Provide && (!B || B->isDefined()))
192 Cmd->Sym = addRegularSymbol(Cmd);
195 bool SymbolAssignment::classof(const BaseCommand *C) {
196 return C->Kind == AssignmentKind;
199 bool OutputSectionCommand::classof(const BaseCommand *C) {
200 return C->Kind == OutputSectionKind;
203 // Fill [Buf, Buf + Size) with Filler.
204 // This is used for linker script "=fillexp" command.
205 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
207 for (; I + 4 < Size; I += 4)
208 memcpy(Buf + I, &Filler, 4);
209 memcpy(Buf + I, &Filler, Size - I);
212 bool InputSectionDescription::classof(const BaseCommand *C) {
213 return C->Kind == InputSectionKind;
216 bool AssertCommand::classof(const BaseCommand *C) {
217 return C->Kind == AssertKind;
220 bool BytesDataCommand::classof(const BaseCommand *C) {
221 return C->Kind == BytesDataKind;
224 static StringRef basename(InputSectionBase *S) {
226 return sys::path::filename(S->File->getName());
230 bool LinkerScript::shouldKeep(InputSectionBase *S) {
231 for (InputSectionDescription *ID : Opt.KeptSections)
232 if (ID->FilePat.match(basename(S)))
233 for (SectionPattern &P : ID->SectionPatterns)
234 if (P.SectionPat.match(S->Name))
239 // A helper function for the SORT() command.
240 static std::function<bool(InputSectionBase *, InputSectionBase *)>
241 getComparator(SortSectionPolicy K) {
243 case SortSectionPolicy::Alignment:
244 return [](InputSectionBase *A, InputSectionBase *B) {
245 // ">" is not a mistake. Sections with larger alignments are placed
246 // before sections with smaller alignments in order to reduce the
247 // amount of padding necessary. This is compatible with GNU.
248 return A->Alignment > B->Alignment;
250 case SortSectionPolicy::Name:
251 return [](InputSectionBase *A, InputSectionBase *B) {
252 return A->Name < B->Name;
254 case SortSectionPolicy::Priority:
255 return [](InputSectionBase *A, InputSectionBase *B) {
256 return getPriority(A->Name) < getPriority(B->Name);
259 llvm_unreachable("unknown sort policy");
263 // A helper function for the SORT() command.
264 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
265 ConstraintKind Kind) {
266 if (Kind == ConstraintKind::NoConstraint)
269 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
270 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
273 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
274 (!IsRW && Kind == ConstraintKind::ReadOnly);
277 static void sortSections(InputSection **Begin, InputSection **End,
278 SortSectionPolicy K) {
279 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
280 std::stable_sort(Begin, End, getComparator(K));
283 // Compute and remember which sections the InputSectionDescription matches.
284 std::vector<InputSection *>
285 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
286 std::vector<InputSection *> Ret;
288 // Collects all sections that satisfy constraints of Cmd.
289 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
290 size_t SizeBefore = Ret.size();
292 for (InputSectionBase *Sec : InputSections) {
297 reportDiscarded(Sec);
301 // For -emit-relocs we have to ignore entries like
302 // .rela.dyn : { *(.rela.data) }
303 // which are common because they are in the default bfd script.
304 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
307 StringRef Filename = basename(Sec);
308 if (!Cmd->FilePat.match(Filename) ||
309 Pat.ExcludedFilePat.match(Filename) ||
310 !Pat.SectionPat.match(Sec->Name))
313 Ret.push_back(cast<InputSection>(Sec));
314 Sec->Assigned = true;
317 // Sort sections as instructed by SORT-family commands and --sort-section
318 // option. Because SORT-family commands can be nested at most two depth
319 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
320 // line option is respected even if a SORT command is given, the exact
321 // behavior we have here is a bit complicated. Here are the rules.
323 // 1. If two SORT commands are given, --sort-section is ignored.
324 // 2. If one SORT command is given, and if it is not SORT_NONE,
325 // --sort-section is handled as an inner SORT command.
326 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
327 // 4. If no SORT command is given, sort according to --sort-section.
328 InputSection **Begin = Ret.data() + SizeBefore;
329 InputSection **End = Ret.data() + Ret.size();
330 if (Pat.SortOuter != SortSectionPolicy::None) {
331 if (Pat.SortInner == SortSectionPolicy::Default)
332 sortSections(Begin, End, Config->SortSection);
334 sortSections(Begin, End, Pat.SortInner);
335 sortSections(Begin, End, Pat.SortOuter);
341 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
342 for (InputSectionBase *S : V) {
344 if (S == InX::ShStrTab)
345 error("discarding .shstrtab section is not allowed");
346 discard(S->DependentSections);
350 std::vector<InputSectionBase *>
351 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
352 std::vector<InputSectionBase *> Ret;
354 for (BaseCommand *Base : OutCmd.Commands) {
355 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
359 Cmd->Sections = computeInputSections(Cmd);
360 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
366 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
367 // A symbol can be assigned before any section is mentioned in the linker
368 // script. In an DSO, the symbol values are addresses, so the only important
369 // section values are:
372 // * Any value meaning a regular section.
373 // To handle that, create a dummy aether section that fills the void before
374 // the linker scripts switches to another section. It has an index of one
375 // which will map to whatever the first actual section is.
376 Aether = make<OutputSection>("", 0, SHF_ALLOC);
377 Aether->SectionIndex = 1;
381 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
382 // Handle symbol assignments outside of any output section.
383 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
388 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
389 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
391 // The output section name `/DISCARD/' is special.
392 // Any input section assigned to it is discarded.
393 if (Cmd->Name == "/DISCARD/") {
398 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
399 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
400 // sections satisfy a given constraint. If not, a directive is handled
401 // as if it wasn't present from the beginning.
403 // Because we'll iterate over Commands many more times, the easiest
404 // way to "make it as if it wasn't present" is to just remove it.
405 if (!matchConstraints(V, Cmd->Constraint)) {
406 for (InputSectionBase *S : V)
408 Opt.Commands.erase(Opt.Commands.begin() + I);
413 // A directive may contain symbol definitions like this:
414 // ".foo : { ...; bar = .; }". Handle them.
415 for (BaseCommand *Base : Cmd->Commands)
416 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
419 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
420 // is given, input sections are aligned to that value, whether the
421 // given value is larger or smaller than the original section alignment.
422 if (Cmd->SubalignExpr) {
423 uint32_t Subalign = Cmd->SubalignExpr().getValue();
424 for (InputSectionBase *S : V)
425 S->Alignment = Subalign;
428 // Add input sections to an output section.
429 for (InputSectionBase *S : V)
430 Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
431 if (OutputSection *Sec = Cmd->Sec) {
432 assert(Sec->SectionIndex == INT_MAX);
433 Sec->SectionIndex = I;
435 Sec->Type = SHT_NOBITS;
436 SecToCommand[Sec] = Cmd;
443 void LinkerScript::fabricateDefaultCommands() {
444 std::vector<BaseCommand *> Commands;
446 // Define start address
447 uint64_t StartAddr = -1;
449 // The Sections with -T<section> have been sorted in order of ascending
450 // address. We must lower StartAddr if the lowest -T<section address> as
451 // calls to setDot() must be monotonically increasing.
452 for (auto& KV : Config->SectionStartMap)
453 StartAddr = std::min(StartAddr, KV.second);
455 Commands.push_back(make<SymbolAssignment>(
458 return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
462 // For each OutputSection that needs a VA fabricate an OutputSectionCommand
463 // with an InputSectionDescription describing the InputSections
464 for (OutputSection *Sec : *OutputSections) {
465 auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>");
467 SecToCommand[Sec] = OSCmd;
469 // Prefer user supplied address over additional alignment constraint
470 auto I = Config->SectionStartMap.find(Sec->Name);
471 if (I != Config->SectionStartMap.end())
472 OSCmd->AddrExpr = [=] { return I->second; };
474 Commands.push_back(OSCmd);
475 if (Sec->Sections.size()) {
476 auto *ISD = make<InputSectionDescription>("");
477 OSCmd->Commands.push_back(ISD);
478 for (InputSection *ISec : Sec->Sections) {
479 ISD->Sections.push_back(ISec);
480 ISec->Assigned = true;
484 // SECTIONS commands run before other non SECTIONS commands
485 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
486 Opt.Commands = std::move(Commands);
489 // Add sections that didn't match any sections command.
490 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
491 for (InputSectionBase *S : InputSections) {
492 if (!S->Live || S->Parent)
494 StringRef Name = getOutputSectionName(S->Name);
495 auto I = std::find_if(
496 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
497 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
498 return Cmd->Name == Name;
501 if (I == Opt.Commands.end()) {
502 Factory.addInputSec(S, Name);
504 auto *Cmd = cast<OutputSectionCommand>(*I);
505 Factory.addInputSec(S, Name, Cmd->Sec);
506 if (OutputSection *Sec = Cmd->Sec) {
507 SecToCommand[Sec] = Cmd;
508 unsigned Index = std::distance(Opt.Commands.begin(), I);
509 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
510 Sec->SectionIndex = Index;
512 auto *ISD = make<InputSectionDescription>("");
513 ISD->Sections.push_back(cast<InputSection>(S));
514 Cmd->Commands.push_back(ISD);
519 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
520 bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
521 uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
522 Start = alignTo(Start, Align);
523 uint64_t End = Start + Size;
526 ThreadBssOffset = End - Dot;
532 void LinkerScript::output(InputSection *S) {
533 uint64_t Pos = advance(S->getSize(), S->Alignment);
534 S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
536 // Update output section size after adding each section. This is so that
537 // SIZEOF works correctly in the case below:
538 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
539 CurOutSec->Size = Pos - CurOutSec->Addr;
541 // If there is a memory region associated with this input section, then
542 // place the section in that region and update the region index.
544 CurMemRegion->Offset += CurOutSec->Size;
545 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
546 if (CurSize > CurMemRegion->Length) {
547 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
548 error("section '" + CurOutSec->Name + "' will not fit in region '" +
549 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
555 void LinkerScript::switchTo(OutputSection *Sec) {
556 if (CurOutSec == Sec)
560 CurOutSec->Addr = advance(0, CurOutSec->Alignment);
562 // If neither AT nor AT> is specified for an allocatable section, the linker
563 // will set the LMA such that the difference between VMA and LMA for the
564 // section is the same as the preceding output section in the same region
565 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
567 CurOutSec->LMAOffset = LMAOffset();
570 void LinkerScript::process(BaseCommand &Base) {
571 // This handles the assignments to symbol or to the dot.
572 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
573 assignSymbol(Cmd, true);
577 // Handle BYTE(), SHORT(), LONG(), or QUAD().
578 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
579 Cmd->Offset = Dot - CurOutSec->Addr;
581 CurOutSec->Size = Dot - CurOutSec->Addr;
586 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
591 // Handle a single input section description command.
592 // It calculates and assigns the offsets for each section and also
593 // updates the output section size.
594 auto &Cmd = cast<InputSectionDescription>(Base);
595 for (InputSection *Sec : Cmd.Sections) {
596 // We tentatively added all synthetic sections at the beginning and removed
597 // empty ones afterwards (because there is no way to know whether they were
598 // going be empty or not other than actually running linker scripts.)
599 // We need to ignore remains of empty sections.
600 if (auto *S = dyn_cast<SyntheticSection>(Sec))
606 assert(CurOutSec == Sec->getParent());
611 // This function searches for a memory region to place the given output
612 // section in. If found, a pointer to the appropriate memory region is
613 // returned. Otherwise, a nullptr is returned.
614 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
615 // If a memory region name was specified in the output section command,
616 // then try to find that region first.
617 if (!Cmd->MemoryRegionName.empty()) {
618 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
619 if (It != Opt.MemoryRegions.end())
621 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
625 // If at least one memory region is defined, all sections must
626 // belong to some memory region. Otherwise, we don't need to do
627 // anything for memory regions.
628 if (Opt.MemoryRegions.empty())
631 OutputSection *Sec = Cmd->Sec;
632 // See if a region can be found by matching section flags.
633 for (auto &Pair : Opt.MemoryRegions) {
634 MemoryRegion &M = Pair.second;
635 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
639 // Otherwise, no suitable region was found.
640 if (Sec->Flags & SHF_ALLOC)
641 error("no memory region specified for section '" + Sec->Name + "'");
645 // This function assigns offsets to input sections and an output section
646 // for a single sections command (e.g. ".text { *(.text); }").
647 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
648 OutputSection *Sec = Cmd->Sec;
652 if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
653 setDot(Cmd->AddrExpr, Cmd->Location, false);
657 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
660 CurMemRegion = Cmd->MemRegion;
662 Dot = CurMemRegion->Offset;
665 // We do not support custom layout for compressed debug sectons.
666 // At this point we already know their size and have compressed content.
667 if (CurOutSec->Flags & SHF_COMPRESSED)
670 for (BaseCommand *C : Cmd->Commands)
674 void LinkerScript::removeEmptyCommands() {
675 // It is common practice to use very generic linker scripts. So for any
676 // given run some of the output sections in the script will be empty.
677 // We could create corresponding empty output sections, but that would
678 // clutter the output.
679 // We instead remove trivially empty sections. The bfd linker seems even
680 // more aggressive at removing them.
681 auto Pos = std::remove_if(
682 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
683 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
684 return std::find(OutputSections->begin(), OutputSections->end(),
685 Cmd->Sec) == OutputSections->end();
688 Opt.Commands.erase(Pos, Opt.Commands.end());
691 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
692 for (BaseCommand *Base : Cmd.Commands)
693 if (!isa<InputSectionDescription>(*Base))
698 void LinkerScript::adjustSectionsBeforeSorting() {
699 // If the output section contains only symbol assignments, create a
700 // corresponding output section. The bfd linker seems to only create them if
701 // '.' is assigned to, but creating these section should not have any bad
702 // consequeces and gives us a section to put the symbol in.
703 uint64_t Flags = SHF_ALLOC;
705 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
706 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
709 if (OutputSection *Sec = Cmd->Sec) {
714 if (isAllSectionDescription(*Cmd))
717 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
718 OutSec->SectionIndex = I;
719 OutputSections->push_back(OutSec);
721 SecToCommand[OutSec] = Cmd;
725 void LinkerScript::adjustSectionsAfterSorting() {
726 placeOrphanSections();
728 // Try and find an appropriate memory region to assign offsets in.
729 for (BaseCommand *Base : Opt.Commands) {
730 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
731 Cmd->MemRegion = findMemoryRegion(Cmd);
732 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
734 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
738 // If output section command doesn't specify any segments,
739 // and we haven't previously assigned any section to segment,
740 // then we simply assign section to the very first load segment.
741 // Below is an example of such linker script:
742 // PHDRS { seg PT_LOAD; }
743 // SECTIONS { .aaa : { *(.aaa) } }
744 std::vector<StringRef> DefPhdrs;
746 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
747 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
748 if (FirstPtLoad != Opt.PhdrsCommands.end())
749 DefPhdrs.push_back(FirstPtLoad->Name);
751 // Walk the commands and propagate the program headers to commands that don't
752 // explicitly specify them.
753 for (BaseCommand *Base : Opt.Commands) {
754 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
758 if (Cmd->Phdrs.empty())
759 Cmd->Phdrs = DefPhdrs;
761 DefPhdrs = Cmd->Phdrs;
764 removeEmptyCommands();
767 // When placing orphan sections, we want to place them after symbol assignments
768 // so that an orphan after
772 // doesn't break the intended meaning of the begin/end symbols.
773 // We don't want to go over sections since Writer<ELFT>::sortSections is the
774 // one in charge of deciding the order of the sections.
775 // We don't want to go over alignments, since doing so in
776 // rx_sec : { *(rx_sec) }
777 // . = ALIGN(0x1000);
778 // /* The RW PT_LOAD starts here*/
779 // rw_sec : { *(rw_sec) }
780 // would mean that the RW PT_LOAD would become unaligned.
781 static bool shouldSkip(BaseCommand *Cmd) {
782 if (isa<OutputSectionCommand>(Cmd))
784 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
785 return Assign->Name != ".";
789 // Orphan sections are sections present in the input files which are
790 // not explicitly placed into the output file by the linker script.
792 // When the control reaches this function, Opt.Commands contains
793 // output section commands for non-orphan sections only. This function
794 // adds new elements for orphan sections so that all sections are
795 // explicitly handled by Opt.Commands.
797 // Writer<ELFT>::sortSections has already sorted output sections.
798 // What we need to do is to scan OutputSections vector and
799 // Opt.Commands in parallel to find orphan sections. If there is an
800 // output section that doesn't have a corresponding entry in
801 // Opt.Commands, we will insert a new entry to Opt.Commands.
803 // There is some ambiguity as to where exactly a new entry should be
804 // inserted, because Opt.Commands contains not only output section
805 // commands but also other types of commands such as symbol assignment
806 // expressions. There's no correct answer here due to the lack of the
807 // formal specification of the linker script. We use heuristics to
808 // determine whether a new output command should be added before or
809 // after another commands. For the details, look at shouldSkip
811 void LinkerScript::placeOrphanSections() {
812 // The OutputSections are already in the correct order.
813 // This loops creates or moves commands as needed so that they are in the
817 // As a horrible special case, skip the first . assignment if it is before any
818 // section. We do this because it is common to set a load address by starting
819 // the script with ". = 0xabcd" and the expectation is that every section is
821 auto FirstSectionOrDotAssignment =
822 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
823 [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
824 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
825 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
826 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
830 for (OutputSection *Sec : *OutputSections) {
831 StringRef Name = Sec->Name;
833 // Find the last spot where we can insert a command and still get the
835 auto CmdIter = Opt.Commands.begin() + CmdIndex;
836 auto E = Opt.Commands.end();
837 while (CmdIter != E && shouldSkip(*CmdIter)) {
842 // If there is no command corresponding to this output section,
843 // create one and put a InputSectionDescription in it so that both
844 // representations agree on which input sections to use.
845 OutputSectionCommand *Cmd = getCmd(Sec);
847 Cmd = createOutputSectionCommand(Name, "<internal>");
848 Opt.Commands.insert(CmdIter, Cmd);
852 SecToCommand[Sec] = Cmd;
853 auto *ISD = make<InputSectionDescription>("");
854 for (InputSection *IS : Sec->Sections)
855 ISD->Sections.push_back(IS);
856 Cmd->Commands.push_back(ISD);
861 // Continue from where we found it.
862 while (*CmdIter != Cmd) {
870 void LinkerScript::processNonSectionCommands() {
871 for (BaseCommand *Base : Opt.Commands) {
872 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
873 assignSymbol(Cmd, false);
874 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
880 allocateHeaders(std::vector<PhdrEntry> &Phdrs,
881 ArrayRef<OutputSectionCommand *> OutputSectionCommands,
884 std::find_if(Phdrs.begin(), Phdrs.end(),
885 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
886 if (FirstPTLoad == Phdrs.end())
889 uint64_t HeaderSize = getHeaderSize();
890 if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
891 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
892 Out::ElfHeader->Addr = Min;
893 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
897 assert(FirstPTLoad->First == Out::ElfHeader);
898 OutputSection *ActualFirst = nullptr;
899 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
900 OutputSection *Sec = Cmd->Sec;
901 if (Sec->FirstInPtLoad == Out::ElfHeader) {
907 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
908 OutputSection *Sec = Cmd->Sec;
909 if (Sec->FirstInPtLoad == Out::ElfHeader)
910 Sec->FirstInPtLoad = ActualFirst;
912 FirstPTLoad->First = ActualFirst;
914 Phdrs.erase(FirstPTLoad);
917 auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
918 return E.p_type == PT_PHDR;
920 if (PhdrI != Phdrs.end())
925 void LinkerScript::assignAddresses(
926 std::vector<PhdrEntry> &Phdrs,
927 ArrayRef<OutputSectionCommand *> OutputSectionCommands) {
928 // Assign addresses as instructed by linker script SECTIONS sub-commands.
930 ErrorOnMissingSection = true;
933 for (BaseCommand *Base : Opt.Commands) {
934 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
935 assignSymbol(Cmd, false);
939 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
944 auto *Cmd = cast<OutputSectionCommand>(Base);
948 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
949 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
950 OutputSection *Sec = Cmd->Sec;
951 if (Sec->Flags & SHF_ALLOC)
952 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
957 allocateHeaders(Phdrs, OutputSectionCommands, MinVA);
960 // Creates program headers as instructed by PHDRS linker script command.
961 std::vector<PhdrEntry> LinkerScript::createPhdrs() {
962 std::vector<PhdrEntry> Ret;
964 // Process PHDRS and FILEHDR keywords because they are not
965 // real output sections and cannot be added in the following loop.
966 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
967 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
968 PhdrEntry &Phdr = Ret.back();
971 Phdr.add(Out::ElfHeader);
973 Phdr.add(Out::ProgramHeaders);
976 Phdr.p_paddr = Cmd.LMAExpr().getValue();
981 // Add output sections to program headers.
982 for (OutputSection *Sec : *OutputSections) {
983 if (!(Sec->Flags & SHF_ALLOC))
986 // Assign headers specified by linker script
987 for (size_t Id : getPhdrIndices(Sec)) {
989 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
990 Ret[Id].p_flags |= Sec->getPhdrFlags();
996 bool LinkerScript::ignoreInterpSection() {
997 // Ignore .interp section in case we have PHDRS specification
998 // and PT_INTERP isn't listed.
999 if (Opt.PhdrsCommands.empty())
1001 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
1002 if (Cmd.Type == PT_INTERP)
1007 OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
1008 auto I = SecToCommand.find(Sec);
1009 if (I == SecToCommand.end())
1014 uint32_t OutputSectionCommand::getFiller() {
1017 if (Sec->Flags & SHF_EXECINSTR)
1018 return Target->TrapInstr;
1022 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
1026 write16(Buf, Data, Config->Endianness);
1028 write32(Buf, Data, Config->Endianness);
1030 write64(Buf, Data, Config->Endianness);
1032 llvm_unreachable("unsupported Size argument");
1035 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1036 // Synthetic doesn't have link order dependecy, stable_sort will keep it last
1037 if (A->kind() == InputSectionBase::Synthetic ||
1038 B->kind() == InputSectionBase::Synthetic)
1040 InputSection *LA = A->getLinkOrderDep();
1041 InputSection *LB = B->getLinkOrderDep();
1042 OutputSection *AOut = LA->getParent();
1043 OutputSection *BOut = LB->getParent();
1045 return AOut->SectionIndex < BOut->SectionIndex;
1046 return LA->OutSecOff < LB->OutSecOff;
1049 template <class ELFT>
1050 static void finalizeShtGroup(OutputSection *OS,
1051 ArrayRef<InputSection *> Sections) {
1052 // sh_link field for SHT_GROUP sections should contain the section index of
1053 // the symbol table.
1054 OS->Link = InX::SymTab->getParent()->SectionIndex;
1056 // sh_info then contain index of an entry in symbol table section which
1057 // provides signature of the section group.
1058 elf::ObjectFile<ELFT> *Obj = Sections[0]->getFile<ELFT>();
1059 assert(Config->Relocatable && Sections.size() == 1);
1060 ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
1061 OS->Info = InX::SymTab->getSymbolIndex(Symbols[Sections[0]->Info - 1]);
1064 template <class ELFT> void OutputSectionCommand::finalize() {
1065 // Link order may be distributed across several InputSectionDescriptions
1066 // but sort must consider them all at once.
1067 std::vector<InputSection **> ScriptSections;
1068 std::vector<InputSection *> Sections;
1069 for (BaseCommand *Base : Commands)
1070 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1071 for (InputSection *&IS : ISD->Sections) {
1072 ScriptSections.push_back(&IS);
1073 Sections.push_back(IS);
1076 if ((Sec->Flags & SHF_LINK_ORDER)) {
1077 std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
1078 for (int I = 0, N = Sections.size(); I < N; ++I)
1079 *ScriptSections[I] = Sections[I];
1081 // We must preserve the link order dependency of sections with the
1082 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
1083 // need to translate the InputSection sh_link to the OutputSection sh_link,
1084 // all InputSections in the OutputSection have the same dependency.
1085 if (auto *D = Sections.front()->getLinkOrderDep())
1086 Sec->Link = D->getParent()->SectionIndex;
1089 uint32_t Type = Sec->Type;
1090 if (Type == SHT_GROUP) {
1091 finalizeShtGroup<ELFT>(Sec, Sections);
1095 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
1098 InputSection *First = Sections[0];
1099 if (isa<SyntheticSection>(First))
1102 Sec->Link = InX::SymTab->getParent()->SectionIndex;
1103 // sh_info for SHT_REL[A] sections should contain the section header index of
1104 // the section to which the relocation applies.
1105 InputSectionBase *S = First->getRelocatedSection();
1106 Sec->Info = S->getOutputSection()->SectionIndex;
1107 Sec->Flags |= SHF_INFO_LINK;
1110 // Compress section contents if this section contains debug info.
1111 template <class ELFT> void OutputSectionCommand::maybeCompress() {
1112 typedef typename ELFT::Chdr Elf_Chdr;
1114 // Compress only DWARF debug sections.
1115 if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) ||
1116 !Name.startswith(".debug_"))
1119 // Create a section header.
1120 Sec->ZDebugHeader.resize(sizeof(Elf_Chdr));
1121 auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data());
1122 Hdr->ch_type = ELFCOMPRESS_ZLIB;
1123 Hdr->ch_size = Sec->Size;
1124 Hdr->ch_addralign = Sec->Alignment;
1126 // Write section contents to a temporary buffer and compress it.
1127 std::vector<uint8_t> Buf(Sec->Size);
1128 writeTo<ELFT>(Buf.data());
1129 if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData))
1130 fatal("compress failed: " + llvm::toString(std::move(E)));
1132 // Update section headers.
1133 Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size();
1134 Sec->Flags |= SHF_COMPRESSED;
1137 template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
1138 if (Sec->Type == SHT_NOBITS)
1143 // We may have already rendered compressed content when using
1144 // -compress-debug-sections option. Write it together with header.
1145 if (!Sec->CompressedData.empty()) {
1146 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1147 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1148 Sec->CompressedData.size());
1152 // Write leading padding.
1153 std::vector<InputSection *> Sections;
1154 for (BaseCommand *Cmd : Commands)
1155 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
1156 for (InputSection *IS : ISD->Sections)
1158 Sections.push_back(IS);
1159 uint32_t Filler = getFiller();
1161 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1163 parallelForEachN(0, Sections.size(), [=](size_t I) {
1164 InputSection *IS = Sections[I];
1165 IS->writeTo<ELFT>(Buf);
1167 // Fill gaps between sections.
1169 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1171 if (I + 1 == Sections.size())
1172 End = Buf + Sec->Size;
1174 End = Buf + Sections[I + 1]->OutSecOff;
1175 fill(Start, End - Start, Filler);
1179 // Linker scripts may have BYTE()-family commands with which you
1180 // can write arbitrary bytes to the output. Process them if any.
1181 for (BaseCommand *Base : Commands)
1182 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1183 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
1186 bool LinkerScript::hasLMA(OutputSection *Sec) {
1187 if (OutputSectionCommand *Cmd = getCmd(Sec))
1193 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
1195 return {CurOutSec, Dot - CurOutSec->Addr, Loc};
1196 if (SymbolBody *B = findSymbol(S)) {
1197 if (auto *D = dyn_cast<DefinedRegular>(B))
1198 return {D->Section, D->Value, Loc};
1199 if (auto *C = dyn_cast<DefinedCommon>(B))
1200 return {InX::Common, C->Offset, Loc};
1202 error(Loc + ": symbol not found: " + S);
1206 bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
1208 // Returns indices of ELF headers containing specific section. Each index is a
1209 // zero based number of ELF header listed within PHDRS {} script block.
1210 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) {
1211 if (OutputSectionCommand *Cmd = getCmd(Sec)) {
1212 std::vector<size_t> Ret;
1213 for (StringRef PhdrName : Cmd->Phdrs)
1214 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
1220 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1222 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1223 if (Cmd.Name == PhdrName)
1227 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1231 template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1232 template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1233 template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1234 template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);
1236 template void OutputSectionCommand::maybeCompress<ELF32LE>();
1237 template void OutputSectionCommand::maybeCompress<ELF32BE>();
1238 template void OutputSectionCommand::maybeCompress<ELF64LE>();
1239 template void OutputSectionCommand::maybeCompress<ELF64BE>();
1241 template void OutputSectionCommand::finalize<ELF32LE>();
1242 template void OutputSectionCommand::finalize<ELF32BE>();
1243 template void OutputSectionCommand::finalize<ELF64LE>();
1244 template void OutputSectionCommand::finalize<ELF64BE>();