Index: head/contrib/llvm/tools/lld/ELF/LinkerScript.cpp =================================================================== --- head/contrib/llvm/tools/lld/ELF/LinkerScript.cpp (revision 328140) +++ head/contrib/llvm/tools/lld/ELF/LinkerScript.cpp (revision 328141) @@ -1,1017 +1,1026 @@ //===- LinkerScript.cpp ---------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the parser/evaluator of the linker script. // //===----------------------------------------------------------------------===// #include "LinkerScript.h" #include "Config.h" #include "InputSection.h" #include "OutputSections.h" #include "Strings.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Target.h" #include "Writer.h" #include "lld/Common/Memory.h" #include "lld/Common/Threads.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Endian.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include #include #include #include #include #include #include #include using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; LinkerScript *elf::Script; static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) { if (OutputSection *OS = InputSec->getOutputSection()) return OS->Addr; error(Loc + ": unable to evaluate expression: input section " + InputSec->Name + " has no output section assigned"); return 0; } uint64_t ExprValue::getValue() const { if (Sec) return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc), Alignment); return alignTo(Val, Alignment); } uint64_t ExprValue::getSecAddr() const { if (Sec) return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc); return 0; } uint64_t ExprValue::getSectionOffset() const { // If the alignment is trivial, we don't have to compute the full // value to know the offset. This allows this function to succeed in // cases where the output section is not yet known. if (Alignment == 1) return Val; return getValue() - getSecAddr(); } OutputSection *LinkerScript::createOutputSection(StringRef Name, StringRef Location) { OutputSection *&SecRef = NameToOutputSection[Name]; OutputSection *Sec; if (SecRef && SecRef->Location.empty()) { // There was a forward reference. Sec = SecRef; } else { Sec = make(Name, SHT_NOBITS, 0); if (!SecRef) SecRef = Sec; } Sec->Location = Location; return Sec; } OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) { OutputSection *&CmdRef = NameToOutputSection[Name]; if (!CmdRef) CmdRef = make(Name, SHT_PROGBITS, 0); return CmdRef; } void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { uint64_t Val = E().getValue(); if (Val < Dot && InSec) error(Loc + ": unable to move location counter backward for: " + Ctx->OutSec->Name); Dot = Val; // Update to location counter means update to section size. if (InSec) Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; } // This function is called from processSectionCommands, // while we are fixing the output section layout. void LinkerScript::addSymbol(SymbolAssignment *Cmd) { if (Cmd->Name == ".") return; // If a symbol was in PROVIDE(), we need to define it only when // it is a referenced undefined symbol. Symbol *B = Symtab->find(Cmd->Name); if (Cmd->Provide && (!B || B->isDefined())) return; // Define a symbol. Symbol *Sym; uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false, /*File*/ nullptr); ExprValue Value = Cmd->Expression(); SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; // When this function is called, section addresses have not been // fixed yet. So, we may or may not know the value of the RHS // expression. // // For example, if an expression is `x = 42`, we know x is always 42. // However, if an expression is `x = .`, there's no way to know its // value at the moment. // // We want to set symbol values early if we can. This allows us to // use symbols as variables in linker scripts. Doing so allows us to // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`. uint64_t SymValue = Value.Sec ? 0 : Value.getValue(); replaceSymbol(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility, STT_NOTYPE, SymValue, 0, Sec); Cmd->Sym = cast(Sym); } // This function is called from assignAddresses, while we are // fixing the output section addresses. This function is supposed // to set the final value for a given symbol assignment. void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { if (Cmd->Name == ".") { setDot(Cmd->Expression, Cmd->Location, InSec); return; } if (!Cmd->Sym) return; ExprValue V = Cmd->Expression(); if (V.isAbsolute()) { Cmd->Sym->Section = nullptr; Cmd->Sym->Value = V.getValue(); } else { Cmd->Sym->Section = V.Sec; Cmd->Sym->Value = V.getSectionOffset(); } } static std::string getFilename(InputFile *File) { if (!File) return ""; if (File->ArchiveName.empty()) return File->getName(); return (File->ArchiveName + "(" + File->getName() + ")").str(); } bool LinkerScript::shouldKeep(InputSectionBase *S) { if (KeptSections.empty()) return false; std::string Filename = getFilename(S->File); for (InputSectionDescription *ID : KeptSections) if (ID->FilePat.match(Filename)) for (SectionPattern &P : ID->SectionPatterns) if (P.SectionPat.match(S->Name)) return true; return false; } // A helper function for the SORT() command. static std::function getComparator(SortSectionPolicy K) { switch (K) { case SortSectionPolicy::Alignment: return [](InputSectionBase *A, InputSectionBase *B) { // ">" is not a mistake. Sections with larger alignments are placed // before sections with smaller alignments in order to reduce the // amount of padding necessary. This is compatible with GNU. return A->Alignment > B->Alignment; }; case SortSectionPolicy::Name: return [](InputSectionBase *A, InputSectionBase *B) { return A->Name < B->Name; }; case SortSectionPolicy::Priority: return [](InputSectionBase *A, InputSectionBase *B) { return getPriority(A->Name) < getPriority(B->Name); }; default: llvm_unreachable("unknown sort policy"); } } // A helper function for the SORT() command. static bool matchConstraints(ArrayRef Sections, ConstraintKind Kind) { if (Kind == ConstraintKind::NoConstraint) return true; bool IsRW = llvm::any_of( Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; }); return (IsRW && Kind == ConstraintKind::ReadWrite) || (!IsRW && Kind == ConstraintKind::ReadOnly); } static void sortSections(MutableArrayRef Vec, SortSectionPolicy K) { if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) std::stable_sort(Vec.begin(), Vec.end(), getComparator(K)); } // Sort sections as instructed by SORT-family commands and --sort-section // option. Because SORT-family commands can be nested at most two depth // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command // line option is respected even if a SORT command is given, the exact // behavior we have here is a bit complicated. Here are the rules. // // 1. If two SORT commands are given, --sort-section is ignored. // 2. If one SORT command is given, and if it is not SORT_NONE, // --sort-section is handled as an inner SORT command. // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. // 4. If no SORT command is given, sort according to --sort-section. // 5. If no SORT commands are given and --sort-section is not specified, // apply sorting provided by --symbol-ordering-file if any exist. static void sortInputSections( MutableArrayRef Vec, const SectionPattern &Pat, const DenseMap &Order) { if (Pat.SortOuter == SortSectionPolicy::None) return; if (Pat.SortOuter == SortSectionPolicy::Default && Config->SortSection == SortSectionPolicy::Default) { // If -symbol-ordering-file was given, sort accordingly. // Usually, Order is empty. if (!Order.empty()) sortByOrder(Vec, [&](InputSectionBase *S) { return Order.lookup(S); }); return; } if (Pat.SortInner == SortSectionPolicy::Default) sortSections(Vec, Config->SortSection); else sortSections(Vec, Pat.SortInner); sortSections(Vec, Pat.SortOuter); } // Compute and remember which sections the InputSectionDescription matches. std::vector LinkerScript::computeInputSections(const InputSectionDescription *Cmd, const DenseMap &Order) { std::vector Ret; // Collects all sections that satisfy constraints of Cmd. for (const SectionPattern &Pat : Cmd->SectionPatterns) { size_t SizeBefore = Ret.size(); for (InputSectionBase *Sec : InputSections) { if (!Sec->Live || Sec->Assigned) continue; // For -emit-relocs we have to ignore entries like // .rela.dyn : { *(.rela.data) } // which are common because they are in the default bfd script. if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) continue; std::string Filename = getFilename(Sec->File); if (!Cmd->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename) || !Pat.SectionPat.match(Sec->Name)) continue; // It is safe to assume that Sec is an InputSection // because mergeable or EH input sections have already been // handled and eliminated. Ret.push_back(cast(Sec)); Sec->Assigned = true; } sortInputSections(MutableArrayRef(Ret).slice(SizeBefore), Pat, Order); } return Ret; } void LinkerScript::discard(ArrayRef V) { for (InputSection *S : V) { if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab || S == InX::DynStrTab) error("discarding " + S->Name + " section is not allowed"); S->Assigned = false; S->Live = false; discard(S->DependentSections); } } std::vector LinkerScript::createInputSectionList( OutputSection &OutCmd, const DenseMap &Order) { std::vector Ret; for (BaseCommand *Base : OutCmd.SectionCommands) { if (auto *Cmd = dyn_cast(Base)) { Cmd->Sections = computeInputSections(Cmd, Order); Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); } } return Ret; } void LinkerScript::processSectionCommands() { // A symbol can be assigned before any section is mentioned in the linker // script. In an DSO, the symbol values are addresses, so the only important // section values are: // * SHN_UNDEF // * SHN_ABS // * Any value meaning a regular section. // To handle that, create a dummy aether section that fills the void before // the linker scripts switches to another section. It has an index of one // which will map to whatever the first actual section is. Aether = make("", 0, SHF_ALLOC); Aether->SectionIndex = 1; // Ctx captures the local AddressState and makes it accessible deliberately. // This is needed as there are some cases where we cannot just // thread the current state through to a lambda function created by the // script parser. auto Deleter = make_unique(); Ctx = Deleter.get(); Ctx->OutSec = Aether; size_t I = 0; DenseMap Order = buildSectionOrder(); // Add input sections to output sections. for (BaseCommand *Base : SectionCommands) { // Handle symbol assignments outside of any output section. if (auto *Cmd = dyn_cast(Base)) { addSymbol(Cmd); continue; } if (auto *Sec = dyn_cast(Base)) { std::vector V = createInputSectionList(*Sec, Order); // The output section name `/DISCARD/' is special. // Any input section assigned to it is discarded. if (Sec->Name == "/DISCARD/") { discard(V); continue; } // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input // sections satisfy a given constraint. If not, a directive is handled // as if it wasn't present from the beginning. // // Because we'll iterate over SectionCommands many more times, the easy // way to "make it as if it wasn't present" is to make it empty. if (!matchConstraints(V, Sec->Constraint)) { for (InputSectionBase *S : V) S->Assigned = false; Sec->SectionCommands.clear(); continue; } // A directive may contain symbol definitions like this: // ".foo : { ...; bar = .; }". Handle them. for (BaseCommand *Base : Sec->SectionCommands) if (auto *OutCmd = dyn_cast(Base)) addSymbol(OutCmd); // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign // is given, input sections are aligned to that value, whether the // given value is larger or smaller than the original section alignment. if (Sec->SubalignExpr) { uint32_t Subalign = Sec->SubalignExpr().getValue(); for (InputSectionBase *S : V) S->Alignment = Subalign; } // Add input sections to an output section. for (InputSection *S : V) Sec->addSection(S); Sec->SectionIndex = I++; if (Sec->Noload) Sec->Type = SHT_NOBITS; } } Ctx = nullptr; } static OutputSection *findByName(ArrayRef Vec, StringRef Name) { for (BaseCommand *Base : Vec) if (auto *Sec = dyn_cast(Base)) if (Sec->Name == Name) return Sec; return nullptr; } static OutputSection *createSection(InputSectionBase *IS, StringRef OutsecName) { OutputSection *Sec = Script->createOutputSection(OutsecName, ""); Sec->addSection(cast(IS)); return Sec; } static OutputSection *addInputSec(StringMap &Map, InputSectionBase *IS, StringRef OutsecName) { // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r // option is given. A section with SHT_GROUP defines a "section group", and // its members have SHF_GROUP attribute. Usually these flags have already been // stripped by InputFiles.cpp as section groups are processed and uniquified. // However, for the -r option, we want to pass through all section groups // as-is because adding/removing members or merging them with other groups // change their semantics. if (IS->Type == SHT_GROUP || (IS->Flags & SHF_GROUP)) return createSection(IS, OutsecName); // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have // relocation sections .rela.foo and .rela.bar for example. Most tools do // not allow multiple REL[A] sections for output section. Hence we // should combine these relocation sections into single output. // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any // other REL[A] sections created by linker itself. if (!isa(IS) && (IS->Type == SHT_REL || IS->Type == SHT_RELA)) { auto *Sec = cast(IS); OutputSection *Out = Sec->getRelocatedSection()->getOutputSection(); if (Out->RelocationSection) { Out->RelocationSection->addSection(Sec); return nullptr; } Out->RelocationSection = createSection(IS, OutsecName); return Out->RelocationSection; } // When control reaches here, mergeable sections have already been merged into // synthetic sections. For relocatable case we want to create one output // section per syntetic section so that they have a valid sh_entsize. if (Config->Relocatable && (IS->Flags & SHF_MERGE)) return createSection(IS, OutsecName); // The ELF spec just says // ---------------------------------------------------------------- // In the first phase, input sections that match in name, type and // attribute flags should be concatenated into single sections. // ---------------------------------------------------------------- // // However, it is clear that at least some flags have to be ignored for // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be // ignored. We should not have two output .text sections just because one was // in a group and another was not for example. // // It also seems that that wording was a late addition and didn't get the // necessary scrutiny. // // Merging sections with different flags is expected by some users. One // reason is that if one file has // // int *const bar __attribute__((section(".foo"))) = (int *)0; // // gcc with -fPIC will produce a read only .foo section. But if another // file has // // int zed; // int *const bar __attribute__((section(".foo"))) = (int *)&zed; // // gcc with -fPIC will produce a read write section. // // Last but not least, when using linker script the merge rules are forced by // the script. Unfortunately, linker scripts are name based. This means that // expressions like *(.foo*) can refer to multiple input sections with // different flags. We cannot put them in different output sections or we // would produce wrong results for // // start = .; *(.foo.*) end = .; *(.bar) // // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to // another. The problem is that there is no way to layout those output // sections such that the .foo sections are the only thing between the start // and end symbols. // // Given the above issues, we instead merge sections by name and error on // incompatible types and flags. OutputSection *&Sec = Map[OutsecName]; if (Sec) { Sec->addSection(cast(IS)); return nullptr; } Sec = createSection(IS, OutsecName); return Sec; } // Add sections that didn't match any sections command. void LinkerScript::addOrphanSections() { unsigned End = SectionCommands.size(); StringMap Map; std::vector V; for (InputSectionBase *S : InputSections) { if (!S->Live || S->Parent) continue; StringRef Name = getOutputSectionName(S); if (Config->OrphanHandling == OrphanHandlingPolicy::Error) error(toString(S) + " is being placed in '" + Name + "'"); else if (Config->OrphanHandling == OrphanHandlingPolicy::Warn) warn(toString(S) + " is being placed in '" + Name + "'"); if (OutputSection *Sec = findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) { Sec->addSection(cast(S)); continue; } if (OutputSection *OS = addInputSec(Map, S, Name)) V.push_back(OS); assert(S->getOutputSection()->SectionIndex == INT_MAX); } // If no SECTIONS command was given, we should insert sections commands // before others, so that we can handle scripts which refers them, // for example: "foo = ABSOLUTE(ADDR(.text)));". // When SECTIONS command is present we just add all orphans to the end. if (HasSectionsCommand) SectionCommands.insert(SectionCommands.end(), V.begin(), V.end()); else SectionCommands.insert(SectionCommands.begin(), V.begin(), V.end()); } uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) { bool IsTbss = (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS; uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot; Start = alignTo(Start, Alignment); uint64_t End = Start + Size; if (IsTbss) Ctx->ThreadBssOffset = End - Dot; else Dot = End; return End; } void LinkerScript::output(InputSection *S) { uint64_t Before = advance(0, 1); uint64_t Pos = advance(S->getSize(), S->Alignment); S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr; // Update output section size after adding each section. This is so that // SIZEOF works correctly in the case below: // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } Ctx->OutSec->Size = Pos - Ctx->OutSec->Addr; // If there is a memory region associated with this input section, then // place the section in that region and update the region index. if (Ctx->MemRegion) { uint64_t &CurOffset = Ctx->MemRegionOffset[Ctx->MemRegion]; CurOffset += Pos - Before; uint64_t CurSize = CurOffset - Ctx->MemRegion->Origin; if (CurSize > Ctx->MemRegion->Length) { uint64_t OverflowAmt = CurSize - Ctx->MemRegion->Length; error("section '" + Ctx->OutSec->Name + "' will not fit in region '" + Ctx->MemRegion->Name + "': overflowed by " + Twine(OverflowAmt) + " bytes"); } } } void LinkerScript::switchTo(OutputSection *Sec) { if (Ctx->OutSec == Sec) return; Ctx->OutSec = Sec; Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment); // If neither AT nor AT> is specified for an allocatable section, the linker // will set the LMA such that the difference between VMA and LMA for the // section is the same as the preceding output section in the same region // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html if (Ctx->LMAOffset) Ctx->OutSec->LMAOffset = Ctx->LMAOffset(); } // This function searches for a memory region to place the given output // section in. If found, a pointer to the appropriate memory region is // returned. Otherwise, a nullptr is returned. MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) { // If a memory region name was specified in the output section command, // then try to find that region first. if (!Sec->MemoryRegionName.empty()) { auto It = MemoryRegions.find(Sec->MemoryRegionName); if (It != MemoryRegions.end()) return It->second; error("memory region '" + Sec->MemoryRegionName + "' not declared"); return nullptr; } // If at least one memory region is defined, all sections must // belong to some memory region. Otherwise, we don't need to do // anything for memory regions. if (MemoryRegions.empty()) return nullptr; // See if a region can be found by matching section flags. for (auto &Pair : MemoryRegions) { MemoryRegion *M = Pair.second; if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0) return M; } // Otherwise, no suitable region was found. if (Sec->Flags & SHF_ALLOC) error("no memory region specified for section '" + Sec->Name + "'"); return nullptr; } // This function assigns offsets to input sections and an output section // for a single sections command (e.g. ".text { *(.text); }"). void LinkerScript::assignOffsets(OutputSection *Sec) { if (!(Sec->Flags & SHF_ALLOC)) Dot = 0; else if (Sec->AddrExpr) setDot(Sec->AddrExpr, Sec->Location, false); Ctx->MemRegion = Sec->MemRegion; if (Ctx->MemRegion) Dot = Ctx->MemRegionOffset[Ctx->MemRegion]; if (Sec->LMAExpr) { uint64_t D = Dot; Ctx->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; }; } + if (!Sec->LMARegionName.empty()) { + if (MemoryRegion *MR = MemoryRegions.lookup(Sec->LMARegionName)) { + uint64_t Offset = MR->Origin - Dot; + Ctx->LMAOffset = [=] { return Offset; }; + } else { + error("memory region '" + Sec->LMARegionName + "' not declared"); + } + } + switchTo(Sec); // The Size previously denoted how many InputSections had been added to this // section, and was used for sorting SHF_LINK_ORDER sections. Reset it to // compute the actual size value. Sec->Size = 0; // We visited SectionsCommands from processSectionCommands to // layout sections. Now, we visit SectionsCommands again to fix // section offsets. for (BaseCommand *Base : Sec->SectionCommands) { // This handles the assignments to symbol or to the dot. if (auto *Cmd = dyn_cast(Base)) { assignSymbol(Cmd, true); continue; } // Handle BYTE(), SHORT(), LONG(), or QUAD(). if (auto *Cmd = dyn_cast(Base)) { Cmd->Offset = Dot - Ctx->OutSec->Addr; Dot += Cmd->Size; if (Ctx->MemRegion) Ctx->MemRegionOffset[Ctx->MemRegion] += Cmd->Size; Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; continue; } // Handle ASSERT(). if (auto *Cmd = dyn_cast(Base)) { Cmd->Expression(); continue; } // Handle a single input section description command. // It calculates and assigns the offsets for each section and also // updates the output section size. auto *Cmd = cast(Base); for (InputSection *Sec : Cmd->Sections) { // We tentatively added all synthetic sections at the beginning and // removed empty ones afterwards (because there is no way to know // whether they were going be empty or not other than actually running // linker scripts.) We need to ignore remains of empty sections. if (auto *S = dyn_cast(Sec)) if (S->empty()) continue; if (!Sec->Live) continue; assert(Ctx->OutSec == Sec->getParent()); output(Sec); } } } void LinkerScript::removeEmptyCommands() { // It is common practice to use very generic linker scripts. So for any // given run some of the output sections in the script will be empty. // We could create corresponding empty output sections, but that would // clutter the output. // We instead remove trivially empty sections. The bfd linker seems even // more aggressive at removing them. llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { if (auto *Sec = dyn_cast(Base)) return !Sec->Live; return false; }); } static bool isAllSectionDescription(const OutputSection &Cmd) { for (BaseCommand *Base : Cmd.SectionCommands) if (!isa(*Base)) return false; return true; } void LinkerScript::adjustSectionsBeforeSorting() { // If the output section contains only symbol assignments, create a // corresponding output section. The issue is what to do with linker script // like ".foo : { symbol = 42; }". One option would be to convert it to // "symbol = 42;". That is, move the symbol out of the empty section // description. That seems to be what bfd does for this simple case. The // problem is that this is not completely general. bfd will give up and // create a dummy section too if there is a ". = . + 1" inside the section // for example. // Given that we want to create the section, we have to worry what impact // it will have on the link. For example, if we just create a section with // 0 for flags, it would change which PT_LOADs are created. // We could remember that that particular section is dummy and ignore it in // other parts of the linker, but unfortunately there are quite a few places // that would need to change: // * The program header creation. // * The orphan section placement. // * The address assignment. // The other option is to pick flags that minimize the impact the section // will have on the rest of the linker. That is why we copy the flags from // the previous sections. Only a few flags are needed to keep the impact low. uint64_t Flags = SHF_ALLOC; for (BaseCommand *Cmd : SectionCommands) { auto *Sec = dyn_cast(Cmd); if (!Sec) continue; if (Sec->Live) { Flags = Sec->Flags & (SHF_ALLOC | SHF_WRITE | SHF_EXECINSTR); continue; } if (isAllSectionDescription(*Sec)) continue; Sec->Live = true; Sec->Flags = Flags; } } void LinkerScript::adjustSectionsAfterSorting() { // Try and find an appropriate memory region to assign offsets in. for (BaseCommand *Base : SectionCommands) { if (auto *Sec = dyn_cast(Base)) { if (!Sec->Live) continue; Sec->MemRegion = findMemoryRegion(Sec); // Handle align (e.g. ".foo : ALIGN(16) { ... }"). if (Sec->AlignExpr) Sec->Alignment = std::max(Sec->Alignment, Sec->AlignExpr().getValue()); } } // If output section command doesn't specify any segments, // and we haven't previously assigned any section to segment, // then we simply assign section to the very first load segment. // Below is an example of such linker script: // PHDRS { seg PT_LOAD; } // SECTIONS { .aaa : { *(.aaa) } } std::vector DefPhdrs; auto FirstPtLoad = std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(), [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); if (FirstPtLoad != PhdrsCommands.end()) DefPhdrs.push_back(FirstPtLoad->Name); // Walk the commands and propagate the program headers to commands that don't // explicitly specify them. for (BaseCommand *Base : SectionCommands) { auto *Sec = dyn_cast(Base); if (!Sec) continue; if (Sec->Phdrs.empty()) { // To match the bfd linker script behaviour, only propagate program // headers to sections that are allocated. if (Sec->Flags & SHF_ALLOC) Sec->Phdrs = DefPhdrs; } else { DefPhdrs = Sec->Phdrs; } } } static OutputSection *findFirstSection(PhdrEntry *Load) { for (OutputSection *Sec : OutputSections) if (Sec->PtLoad == Load) return Sec; return nullptr; } // Try to find an address for the file and program headers output sections, // which were unconditionally added to the first PT_LOAD segment earlier. // // When using the default layout, we check if the headers fit below the first // allocated section. When using a linker script, we also check if the headers // are covered by the output section. This allows omitting the headers by not // leaving enough space for them in the linker script; this pattern is common // in embedded systems. // // If there isn't enough space for these sections, we'll remove them from the // PT_LOAD segment, and we'll also remove the PT_PHDR segment. void LinkerScript::allocateHeaders(std::vector &Phdrs) { uint64_t Min = std::numeric_limits::max(); for (OutputSection *Sec : OutputSections) if (Sec->Flags & SHF_ALLOC) Min = std::min(Min, Sec->Addr); auto It = llvm::find_if( Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); if (It == Phdrs.end()) return; PhdrEntry *FirstPTLoad = *It; uint64_t HeaderSize = getHeaderSize(); // When linker script with SECTIONS is being used, don't output headers // unless there's a space for them. uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0; if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) { Min = alignDown(Min - HeaderSize, Config->MaxPageSize); Out::ElfHeader->Addr = Min; Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; return; } Out::ElfHeader->PtLoad = nullptr; Out::ProgramHeaders->PtLoad = nullptr; FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad); llvm::erase_if(Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); } LinkerScript::AddressState::AddressState() { for (auto &MRI : Script->MemoryRegions) { const MemoryRegion *MR = MRI.second; MemRegionOffset[MR] = MR->Origin; } } static uint64_t getInitialDot() { // By default linker scripts use an initial value of 0 for '.', // but prefer -image-base if set. if (Script->HasSectionsCommand) return Config->ImageBase ? *Config->ImageBase : 0; uint64_t StartAddr = UINT64_MAX; // The Sections with -T
have been sorted in order of ascending // address. We must lower StartAddr if the lowest -T
as // calls to setDot() must be monotonically increasing. for (auto &KV : Config->SectionStartMap) StartAddr = std::min(StartAddr, KV.second); return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize()); } // Here we assign addresses as instructed by linker script SECTIONS // sub-commands. Doing that allows us to use final VA values, so here // we also handle rest commands like symbol assignments and ASSERTs. void LinkerScript::assignAddresses() { Dot = getInitialDot(); auto Deleter = make_unique(); Ctx = Deleter.get(); ErrorOnMissingSection = true; switchTo(Aether); for (BaseCommand *Base : SectionCommands) { if (auto *Cmd = dyn_cast(Base)) { assignSymbol(Cmd, false); continue; } if (auto *Cmd = dyn_cast(Base)) { Cmd->Expression(); continue; } assignOffsets(cast(Base)); } Ctx = nullptr; } // Creates program headers as instructed by PHDRS linker script command. std::vector LinkerScript::createPhdrs() { std::vector Ret; // Process PHDRS and FILEHDR keywords because they are not // real output sections and cannot be added in the following loop. for (const PhdrsCommand &Cmd : PhdrsCommands) { PhdrEntry *Phdr = make(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R); if (Cmd.HasFilehdr) Phdr->add(Out::ElfHeader); if (Cmd.HasPhdrs) Phdr->add(Out::ProgramHeaders); if (Cmd.LMAExpr) { Phdr->p_paddr = Cmd.LMAExpr().getValue(); Phdr->HasLMA = true; } Ret.push_back(Phdr); } // Add output sections to program headers. for (OutputSection *Sec : OutputSections) { // Assign headers specified by linker script for (size_t Id : getPhdrIndices(Sec)) { Ret[Id]->add(Sec); if (!PhdrsCommands[Id].Flags.hasValue()) Ret[Id]->p_flags |= Sec->getPhdrFlags(); } } return Ret; } // Returns true if we should emit an .interp section. // // We usually do. But if PHDRS commands are given, and // no PT_INTERP is there, there's no place to emit an // .interp, so we don't do that in that case. bool LinkerScript::needsInterpSection() { if (PhdrsCommands.empty()) return true; for (PhdrsCommand &Cmd : PhdrsCommands) if (Cmd.Type == PT_INTERP) return true; return false; } ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) { if (Name == ".") { if (Ctx) return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc}; error(Loc + ": unable to get location counter value"); return 0; } if (Symbol *Sym = Symtab->find(Name)) { if (auto *DS = dyn_cast(Sym)) return {DS->Section, false, DS->Value, Loc}; if (auto *SS = dyn_cast(Sym)) if (!ErrorOnMissingSection || SS->CopyRelSec) return {SS->CopyRelSec, false, 0, Loc}; } error(Loc + ": symbol not found: " + Name); return 0; } // Returns the index of the segment named Name. static Optional getPhdrIndex(ArrayRef Vec, StringRef Name) { for (size_t I = 0; I < Vec.size(); ++I) if (Vec[I].Name == Name) return I; return None; } // Returns indices of ELF headers containing specific section. Each index is a // zero based number of ELF header listed within PHDRS {} script block. std::vector LinkerScript::getPhdrIndices(OutputSection *Cmd) { std::vector Ret; for (StringRef S : Cmd->Phdrs) { if (Optional Idx = getPhdrIndex(PhdrsCommands, S)) Ret.push_back(*Idx); else if (S != "NONE") error(Cmd->Location + ": section header '" + S + "' is not listed in PHDRS"); } return Ret; } Index: head/contrib/llvm/tools/lld/ELF/OutputSections.h =================================================================== --- head/contrib/llvm/tools/lld/ELF/OutputSections.h (revision 328140) +++ head/contrib/llvm/tools/lld/ELF/OutputSections.h (revision 328141) @@ -1,152 +1,153 @@ //===- OutputSections.h -----------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_ELF_OUTPUT_SECTIONS_H #define LLD_ELF_OUTPUT_SECTIONS_H #include "Config.h" #include "InputSection.h" #include "LinkerScript.h" #include "Relocations.h" #include "lld/Common/LLVM.h" #include "llvm/MC/StringTableBuilder.h" #include "llvm/Object/ELF.h" namespace lld { namespace elf { struct PhdrEntry; class Symbol; struct EhSectionPiece; class EhInputSection; class InputSection; class InputSectionBase; class MergeInputSection; class OutputSection; template class ObjFile; template class SharedFile; class SharedSymbol; class Defined; // This represents a section in an output file. // It is composed of multiple InputSections. // The writer creates multiple OutputSections and assign them unique, // non-overlapping file offsets and VAs. class OutputSection final : public BaseCommand, public SectionBase { public: OutputSection(StringRef Name, uint32_t Type, uint64_t Flags); static bool classof(const SectionBase *S) { return S->kind() == SectionBase::Output; } static bool classof(const BaseCommand *C); uint64_t getLMA() const { return Addr + LMAOffset; } template void writeHeaderTo(typename ELFT::Shdr *SHdr); unsigned SectionIndex; unsigned SortRank; uint32_t getPhdrFlags() const; // Pointer to the PT_LOAD segment, which this section resides in. This field // is used to correctly compute file offset of a section. When two sections // share the same load segment, difference between their file offsets should // be equal to difference between their virtual addresses. To compute some // section offset we use the following formula: Off = Off_first + VA - // VA_first, where Off_first and VA_first is file offset and VA of first // section in PT_LOAD. PhdrEntry *PtLoad = nullptr; // Pointer to a relocation section for this section. Usually nullptr because // we consume relocations, but if --emit-relocs is specified (which is rare), // it may have a non-null value. OutputSection *RelocationSection = nullptr; // Initially this field is the number of InputSections that have been added to // the OutputSection so far. Later on, after a call to assignAddresses, it // corresponds to the Elf_Shdr member. uint64_t Size = 0; // The following fields correspond to Elf_Shdr members. uint64_t Offset = 0; uint64_t LMAOffset = 0; uint64_t Addr = 0; uint32_t ShName = 0; void addSection(InputSection *IS); // Location in the output buffer. uint8_t *Loc = nullptr; // The following members are normally only used in linker scripts. MemoryRegion *MemRegion = nullptr; Expr AddrExpr; Expr AlignExpr; Expr LMAExpr; Expr SubalignExpr; std::vector SectionCommands; std::vector Phdrs; llvm::Optional Filler; ConstraintKind Constraint = ConstraintKind::NoConstraint; std::string Location; std::string MemoryRegionName; + std::string LMARegionName; bool Noload = false; template void finalize(); template void writeTo(uint8_t *Buf); template void maybeCompress(); void sort(std::function Order); void sortInitFini(); void sortCtorsDtors(); private: // Used for implementation of --compress-debug-sections option. std::vector ZDebugHeader; llvm::SmallVector CompressedData; uint32_t getFiller(); }; int getPriority(StringRef S); // All output sections that are handled by the linker specially are // globally accessible. Writer initializes them, so don't use them // until Writer is initialized. struct Out { static uint8_t First; static OutputSection *Opd; static uint8_t *OpdBuf; static PhdrEntry *TlsPhdr; static OutputSection *DebugInfo; static OutputSection *ElfHeader; static OutputSection *ProgramHeaders; static OutputSection *PreinitArray; static OutputSection *InitArray; static OutputSection *FiniArray; }; } // namespace elf } // namespace lld namespace lld { namespace elf { uint64_t getHeaderSize(); void sortByOrder(llvm::MutableArrayRef In, std::function Order); extern std::vector OutputSections; } // namespace elf } // namespace lld #endif Index: head/contrib/llvm/tools/lld/ELF/ScriptParser.cpp =================================================================== --- head/contrib/llvm/tools/lld/ELF/ScriptParser.cpp (revision 328140) +++ head/contrib/llvm/tools/lld/ELF/ScriptParser.cpp (revision 328141) @@ -1,1334 +1,1342 @@ //===- ScriptParser.cpp ---------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a recursive-descendent parser for linker scripts. // Parsed results are stored to Config and Script global objects. // //===----------------------------------------------------------------------===// #include "ScriptParser.h" #include "Config.h" #include "Driver.h" #include "InputSection.h" #include "LinkerScript.h" #include "OutputSections.h" #include "ScriptLexer.h" #include "Symbols.h" #include "Target.h" #include "lld/Common/Memory.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include #include #include using namespace llvm; using namespace llvm::ELF; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; static bool isUnderSysroot(StringRef Path); namespace { class ScriptParser final : ScriptLexer { public: ScriptParser(MemoryBufferRef MB) : ScriptLexer(MB), IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {} void readLinkerScript(); void readVersionScript(); void readDynamicList(); void readDefsym(StringRef Name); private: void addFile(StringRef Path); void readAsNeeded(); void readEntry(); void readExtern(); void readGroup(); void readInclude(); void readMemory(); void readOutput(); void readOutputArch(); void readOutputFormat(); void readPhdrs(); void readRegionAlias(); void readSearchDir(); void readSections(); void readVersion(); void readVersionScriptCommand(); SymbolAssignment *readAssignment(StringRef Name); ByteCommand *readByteCommand(StringRef Tok); uint32_t readFill(); uint32_t parseFill(StringRef Tok); void readSectionAddressType(OutputSection *Cmd); OutputSection *readOutputSectionDescription(StringRef OutSec); std::vector readOutputSectionPhdrs(); InputSectionDescription *readInputSectionDescription(StringRef Tok); StringMatcher readFilePatterns(); std::vector readInputSectionsList(); InputSectionDescription *readInputSectionRules(StringRef FilePattern); unsigned readPhdrType(); SortSectionPolicy readSortKind(); SymbolAssignment *readProvideHidden(bool Provide, bool Hidden); SymbolAssignment *readProvideOrAssignment(StringRef Tok); void readSort(); AssertCommand *readAssert(); Expr readAssertExpr(); Expr readConstant(); Expr getPageSize(); uint64_t readMemoryAssignment(StringRef, StringRef, StringRef); std::pair readMemoryAttributes(); Expr readExpr(); Expr readExpr1(Expr Lhs, int MinPrec); StringRef readParenLiteral(); Expr readPrimary(); Expr readTernary(Expr Cond); Expr readParenExpr(); // For parsing version script. std::vector readVersionExtern(); void readAnonymousDeclaration(); void readVersionDeclaration(StringRef VerStr); std::pair, std::vector> readSymbols(); // True if a script being read is in a subdirectory specified by -sysroot. bool IsUnderSysroot; // A set to detect an INCLUDE() cycle. StringSet<> Seen; }; } // namespace static StringRef unquote(StringRef S) { if (S.startswith("\"")) return S.substr(1, S.size() - 2); return S; } static bool isUnderSysroot(StringRef Path) { if (Config->Sysroot == "") return false; for (; !Path.empty(); Path = sys::path::parent_path(Path)) if (sys::fs::equivalent(Config->Sysroot, Path)) return true; return false; } // Some operations only support one non absolute value. Move the // absolute one to the right hand side for convenience. static void moveAbsRight(ExprValue &A, ExprValue &B) { if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute())) std::swap(A, B); if (!B.isAbsolute()) error(A.Loc + ": at least one side of the expression must be absolute"); } static ExprValue add(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc}; } static ExprValue sub(ExprValue A, ExprValue B) { // The distance between two symbols in sections is absolute. if (!A.isAbsolute() && !B.isAbsolute()) return A.getValue() - B.getValue(); return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc}; } static ExprValue mul(ExprValue A, ExprValue B) { return A.getValue() * B.getValue(); } static ExprValue div(ExprValue A, ExprValue B) { if (uint64_t BV = B.getValue()) return A.getValue() / BV; error("division by zero"); return 0; } static ExprValue bitAnd(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc}; } static ExprValue bitOr(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc}; } void ScriptParser::readDynamicList() { Config->HasDynamicList = true; expect("{"); std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); expect(";"); if (!atEOF()) { setError("EOF expected, but got " + next()); return; } if (!Locals.empty()) { setError("\"local:\" scope not supported in --dynamic-list"); return; } for (SymbolVersion V : Globals) Config->DynamicList.push_back(V); } void ScriptParser::readVersionScript() { readVersionScriptCommand(); if (!atEOF()) setError("EOF expected, but got " + next()); } void ScriptParser::readVersionScriptCommand() { if (consume("{")) { readAnonymousDeclaration(); return; } while (!atEOF() && !errorCount() && peek() != "}") { StringRef VerStr = next(); if (VerStr == "{") { setError("anonymous version definition is used in " "combination with other version definitions"); return; } expect("{"); readVersionDeclaration(VerStr); } } void ScriptParser::readVersion() { expect("{"); readVersionScriptCommand(); expect("}"); } void ScriptParser::readLinkerScript() { while (!atEOF()) { StringRef Tok = next(); if (Tok == ";") continue; if (Tok == "ASSERT") { Script->SectionCommands.push_back(readAssert()); } else if (Tok == "ENTRY") { readEntry(); } else if (Tok == "EXTERN") { readExtern(); } else if (Tok == "GROUP" || Tok == "INPUT") { readGroup(); } else if (Tok == "INCLUDE") { readInclude(); } else if (Tok == "MEMORY") { readMemory(); } else if (Tok == "OUTPUT") { readOutput(); } else if (Tok == "OUTPUT_ARCH") { readOutputArch(); } else if (Tok == "OUTPUT_FORMAT") { readOutputFormat(); } else if (Tok == "PHDRS") { readPhdrs(); } else if (Tok == "REGION_ALIAS") { readRegionAlias(); } else if (Tok == "SEARCH_DIR") { readSearchDir(); } else if (Tok == "SECTIONS") { readSections(); } else if (Tok == "VERSION") { readVersion(); } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) { Script->SectionCommands.push_back(Cmd); } else { setError("unknown directive: " + Tok); } } } void ScriptParser::readDefsym(StringRef Name) { Expr E = readExpr(); if (!atEOF()) setError("EOF expected, but got " + next()); SymbolAssignment *Cmd = make(Name, E, getCurrentLocation()); Script->SectionCommands.push_back(Cmd); } void ScriptParser::addFile(StringRef S) { if (IsUnderSysroot && S.startswith("/")) { SmallString<128> PathData; StringRef Path = (Config->Sysroot + S).toStringRef(PathData); if (sys::fs::exists(Path)) { Driver->addFile(Saver.save(Path), /*WithLOption=*/false); return; } } if (S.startswith("/")) { Driver->addFile(S, /*WithLOption=*/false); } else if (S.startswith("=")) { if (Config->Sysroot.empty()) Driver->addFile(S.substr(1), /*WithLOption=*/false); else Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)), /*WithLOption=*/false); } else if (S.startswith("-l")) { Driver->addLibrary(S.substr(2)); } else if (sys::fs::exists(S)) { Driver->addFile(S, /*WithLOption=*/false); } else { if (Optional Path = findFromSearchPaths(S)) Driver->addFile(Saver.save(*Path), /*WithLOption=*/true); else setError("unable to find " + S); } } void ScriptParser::readAsNeeded() { expect("("); bool Orig = Config->AsNeeded; Config->AsNeeded = true; while (!errorCount() && !consume(")")) addFile(unquote(next())); Config->AsNeeded = Orig; } void ScriptParser::readEntry() { // -e takes predecence over ENTRY(). expect("("); StringRef Tok = next(); if (Config->Entry.empty()) Config->Entry = Tok; expect(")"); } void ScriptParser::readExtern() { expect("("); while (!errorCount() && !consume(")")) Config->Undefined.push_back(next()); } void ScriptParser::readGroup() { expect("("); while (!errorCount() && !consume(")")) { if (consume("AS_NEEDED")) readAsNeeded(); else addFile(unquote(next())); } } void ScriptParser::readInclude() { StringRef Tok = unquote(next()); if (!Seen.insert(Tok).second) { setError("there is a cycle in linker script INCLUDEs"); return; } if (Optional Path = searchLinkerScript(Tok)) { if (Optional MB = readFile(*Path)) tokenize(*MB); return; } setError("cannot find linker script " + Tok); } void ScriptParser::readOutput() { // -o takes predecence over OUTPUT(). expect("("); StringRef Tok = next(); if (Config->OutputFile.empty()) Config->OutputFile = unquote(Tok); expect(")"); } void ScriptParser::readOutputArch() { // OUTPUT_ARCH is ignored for now. expect("("); while (!errorCount() && !consume(")")) skip(); } void ScriptParser::readOutputFormat() { // Error checking only for now. expect("("); skip(); if (consume(")")) return; expect(","); skip(); expect(","); skip(); expect(")"); } void ScriptParser::readPhdrs() { expect("{"); while (!errorCount() && !consume("}")) { PhdrsCommand Cmd; Cmd.Name = next(); Cmd.Type = readPhdrType(); while (!errorCount() && !consume(";")) { if (consume("FILEHDR")) Cmd.HasFilehdr = true; else if (consume("PHDRS")) Cmd.HasPhdrs = true; else if (consume("AT")) Cmd.LMAExpr = readParenExpr(); else if (consume("FLAGS")) Cmd.Flags = readParenExpr()().getValue(); else setError("unexpected header attribute: " + next()); } Script->PhdrsCommands.push_back(Cmd); } } void ScriptParser::readRegionAlias() { expect("("); StringRef Alias = unquote(next()); expect(","); StringRef Name = next(); expect(")"); if (Script->MemoryRegions.count(Alias)) setError("redefinition of memory region '" + Alias + "'"); if (!Script->MemoryRegions.count(Name)) setError("memory region '" + Name + "' is not defined"); Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]}); } void ScriptParser::readSearchDir() { expect("("); StringRef Tok = next(); if (!Config->Nostdlib) Config->SearchPaths.push_back(unquote(Tok)); expect(")"); } void ScriptParser::readSections() { Script->HasSectionsCommand = true; // -no-rosegment is used to avoid placing read only non-executable sections in // their own segment. We do the same if SECTIONS command is present in linker // script. See comment for computeFlags(). Config->SingleRoRx = true; expect("{"); while (!errorCount() && !consume("}")) { StringRef Tok = next(); BaseCommand *Cmd = readProvideOrAssignment(Tok); if (!Cmd) { if (Tok == "ASSERT") Cmd = readAssert(); else Cmd = readOutputSectionDescription(Tok); } Script->SectionCommands.push_back(Cmd); } } static int precedence(StringRef Op) { return StringSwitch(Op) .Cases("*", "/", 5) .Cases("+", "-", 4) .Cases("<<", ">>", 3) .Cases("<", "<=", ">", ">=", "==", "!=", 2) .Cases("&", "|", 1) .Default(-1); } StringMatcher ScriptParser::readFilePatterns() { std::vector V; while (!errorCount() && !consume(")")) V.push_back(next()); return StringMatcher(V); } SortSectionPolicy ScriptParser::readSortKind() { if (consume("SORT") || consume("SORT_BY_NAME")) return SortSectionPolicy::Name; if (consume("SORT_BY_ALIGNMENT")) return SortSectionPolicy::Alignment; if (consume("SORT_BY_INIT_PRIORITY")) return SortSectionPolicy::Priority; if (consume("SORT_NONE")) return SortSectionPolicy::None; return SortSectionPolicy::Default; } // Reads SECTIONS command contents in the following form: // // ::= * // ::= ? // ::= "EXCLUDE_FILE" "(" + ")" // // For example, // // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz) // // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o". // The semantics of that is section .foo in any file, section .bar in // any file but a.o, and section .baz in any file but b.o. std::vector ScriptParser::readInputSectionsList() { std::vector Ret; while (!errorCount() && peek() != ")") { StringMatcher ExcludeFilePat; if (consume("EXCLUDE_FILE")) { expect("("); ExcludeFilePat = readFilePatterns(); } std::vector V; while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE") V.push_back(next()); if (!V.empty()) Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)}); else setError("section pattern is expected"); } return Ret; } // Reads contents of "SECTIONS" directive. That directive contains a // list of glob patterns for input sections. The grammar is as follows. // // ::= // | "(" ")" // | "(" "(" ")" ")" // // ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" // // is parsed by readInputSectionsList(). InputSectionDescription * ScriptParser::readInputSectionRules(StringRef FilePattern) { auto *Cmd = make(FilePattern); expect("("); while (!errorCount() && !consume(")")) { SortSectionPolicy Outer = readSortKind(); SortSectionPolicy Inner = SortSectionPolicy::Default; std::vector V; if (Outer != SortSectionPolicy::Default) { expect("("); Inner = readSortKind(); if (Inner != SortSectionPolicy::Default) { expect("("); V = readInputSectionsList(); expect(")"); } else { V = readInputSectionsList(); } expect(")"); } else { V = readInputSectionsList(); } for (SectionPattern &Pat : V) { Pat.SortInner = Inner; Pat.SortOuter = Outer; } std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns)); } return Cmd; } InputSectionDescription * ScriptParser::readInputSectionDescription(StringRef Tok) { // Input section wildcard can be surrounded by KEEP. // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep if (Tok == "KEEP") { expect("("); StringRef FilePattern = next(); InputSectionDescription *Cmd = readInputSectionRules(FilePattern); expect(")"); Script->KeptSections.push_back(Cmd); return Cmd; } return readInputSectionRules(Tok); } void ScriptParser::readSort() { expect("("); expect("CONSTRUCTORS"); expect(")"); } AssertCommand *ScriptParser::readAssert() { return make(readAssertExpr()); } Expr ScriptParser::readAssertExpr() { expect("("); Expr E = readExpr(); expect(","); StringRef Msg = unquote(next()); expect(")"); return [=] { if (!E().getValue()) error(Msg); return Script->getDot(); }; } // Reads a FILL(expr) command. We handle the FILL command as an // alias for =fillexp section attribute, which is different from // what GNU linkers do. // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html uint32_t ScriptParser::readFill() { expect("("); uint32_t V = parseFill(next()); expect(")"); return V; } // Reads an expression and/or the special directive "(NOLOAD)" for an // output section definition. // // An output section name can be followed by an address expression // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be // interpreted as either the beginning of some expression or "(NOLOAD)". // // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html void ScriptParser::readSectionAddressType(OutputSection *Cmd) { if (consume("(")) { if (consume("NOLOAD")) { expect(")"); Cmd->Noload = true; return; } Cmd->AddrExpr = readExpr(); expect(")"); } else { Cmd->AddrExpr = readExpr(); } if (consume("(")) { expect("NOLOAD"); expect(")"); Cmd->Noload = true; } } static Expr checkAlignment(Expr E, std::string &Loc) { return [=] { uint64_t Alignment = std::max((uint64_t)1, E().getValue()); if (!isPowerOf2_64(Alignment)) { error(Loc + ": alignment must be power of 2"); return (uint64_t)1; // Return a dummy value. } return Alignment; }; } OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) { OutputSection *Cmd = Script->createOutputSection(OutSec, getCurrentLocation()); if (peek() != ":") readSectionAddressType(Cmd); expect(":"); std::string Location = getCurrentLocation(); if (consume("AT")) Cmd->LMAExpr = readParenExpr(); if (consume("ALIGN")) Cmd->AlignExpr = checkAlignment(readParenExpr(), Location); if (consume("SUBALIGN")) Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location); // Parse constraints. if (consume("ONLY_IF_RO")) Cmd->Constraint = ConstraintKind::ReadOnly; if (consume("ONLY_IF_RW")) Cmd->Constraint = ConstraintKind::ReadWrite; expect("{"); while (!errorCount() && !consume("}")) { StringRef Tok = next(); if (Tok == ";") { // Empty commands are allowed. Do nothing here. } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) { Cmd->SectionCommands.push_back(Assign); } else if (ByteCommand *Data = readByteCommand(Tok)) { Cmd->SectionCommands.push_back(Data); } else if (Tok == "ASSERT") { Cmd->SectionCommands.push_back(readAssert()); expect(";"); } else if (Tok == "CONSTRUCTORS") { // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors // by name. This is for very old file formats such as ECOFF/XCOFF. // For ELF, we should ignore. } else if (Tok == "FILL") { Cmd->Filler = readFill(); } else if (Tok == "SORT") { readSort(); } else if (peek() == "(") { Cmd->SectionCommands.push_back(readInputSectionDescription(Tok)); } else { setError("unknown command " + Tok); } } if (consume(">")) Cmd->MemoryRegionName = next(); + if (consume("AT")) { + expect(">"); + Cmd->LMARegionName = next(); + } + + if (Cmd->LMAExpr && !Cmd->LMARegionName.empty()) + error("section can't have both LMA and a load region"); + Cmd->Phdrs = readOutputSectionPhdrs(); if (consume("=")) Cmd->Filler = parseFill(next()); else if (peek().startswith("=")) Cmd->Filler = parseFill(next().drop_front()); // Consume optional comma following output section command. consume(","); return Cmd; } // Parses a given string as a octal/decimal/hexadecimal number and // returns it as a big-endian number. Used for `=`. // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html // // When reading a hexstring, ld.bfd handles it as a blob of arbitrary // size, while ld.gold always handles it as a 32-bit big-endian number. // We are compatible with ld.gold because it's easier to implement. uint32_t ScriptParser::parseFill(StringRef Tok) { uint32_t V = 0; if (!to_integer(Tok, V)) setError("invalid filler expression: " + Tok); uint32_t Buf; write32be(&Buf, V); return Buf; } SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) { expect("("); SymbolAssignment *Cmd = readAssignment(next()); Cmd->Provide = Provide; Cmd->Hidden = Hidden; expect(")"); expect(";"); return Cmd; } SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) { SymbolAssignment *Cmd = nullptr; if (peek() == "=" || peek() == "+=") { Cmd = readAssignment(Tok); expect(";"); } else if (Tok == "PROVIDE") { Cmd = readProvideHidden(true, false); } else if (Tok == "HIDDEN") { Cmd = readProvideHidden(false, true); } else if (Tok == "PROVIDE_HIDDEN") { Cmd = readProvideHidden(true, true); } return Cmd; } SymbolAssignment *ScriptParser::readAssignment(StringRef Name) { StringRef Op = next(); assert(Op == "=" || Op == "+="); Expr E = readExpr(); if (Op == "+=") { std::string Loc = getCurrentLocation(); E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); }; } return make(Name, E, getCurrentLocation()); } // This is an operator-precedence parser to parse a linker // script expression. Expr ScriptParser::readExpr() { // Our lexer is context-aware. Set the in-expression bit so that // they apply different tokenization rules. bool Orig = InExpr; InExpr = true; Expr E = readExpr1(readPrimary(), 0); InExpr = Orig; return E; } static Expr combine(StringRef Op, Expr L, Expr R) { if (Op == "+") return [=] { return add(L(), R()); }; if (Op == "-") return [=] { return sub(L(), R()); }; if (Op == "*") return [=] { return mul(L(), R()); }; if (Op == "/") return [=] { return div(L(), R()); }; if (Op == "<<") return [=] { return L().getValue() << R().getValue(); }; if (Op == ">>") return [=] { return L().getValue() >> R().getValue(); }; if (Op == "<") return [=] { return L().getValue() < R().getValue(); }; if (Op == ">") return [=] { return L().getValue() > R().getValue(); }; if (Op == ">=") return [=] { return L().getValue() >= R().getValue(); }; if (Op == "<=") return [=] { return L().getValue() <= R().getValue(); }; if (Op == "==") return [=] { return L().getValue() == R().getValue(); }; if (Op == "!=") return [=] { return L().getValue() != R().getValue(); }; if (Op == "&") return [=] { return bitAnd(L(), R()); }; if (Op == "|") return [=] { return bitOr(L(), R()); }; llvm_unreachable("invalid operator"); } // This is a part of the operator-precedence parser. This function // assumes that the remaining token stream starts with an operator. Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { while (!atEOF() && !errorCount()) { // Read an operator and an expression. if (consume("?")) return readTernary(Lhs); StringRef Op1 = peek(); if (precedence(Op1) < MinPrec) break; skip(); Expr Rhs = readPrimary(); // Evaluate the remaining part of the expression first if the // next operator has greater precedence than the previous one. // For example, if we have read "+" and "3", and if the next // operator is "*", then we'll evaluate 3 * ... part first. while (!atEOF()) { StringRef Op2 = peek(); if (precedence(Op2) <= precedence(Op1)) break; Rhs = readExpr1(Rhs, precedence(Op2)); } Lhs = combine(Op1, Lhs, Rhs); } return Lhs; } Expr ScriptParser::getPageSize() { std::string Location = getCurrentLocation(); return [=]() -> uint64_t { if (Target) return Target->PageSize; error(Location + ": unable to calculate page size"); return 4096; // Return a dummy value. }; } Expr ScriptParser::readConstant() { StringRef S = readParenLiteral(); if (S == "COMMONPAGESIZE") return getPageSize(); if (S == "MAXPAGESIZE") return [] { return Config->MaxPageSize; }; setError("unknown constant: " + S); return {}; } // Parses Tok as an integer. It recognizes hexadecimal (prefixed with // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may // have "K" (Ki) or "M" (Mi) suffixes. static Optional parseInt(StringRef Tok) { // Negative number if (Tok.startswith("-")) { if (Optional Val = parseInt(Tok.substr(1))) return -*Val; return None; } // Hexadecimal uint64_t Val; if (Tok.startswith_lower("0x")) { if (!to_integer(Tok.substr(2), Val, 16)) return None; return Val; } if (Tok.endswith_lower("H")) { if (!to_integer(Tok.drop_back(), Val, 16)) return None; return Val; } // Decimal if (Tok.endswith_lower("K")) { if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024; } if (Tok.endswith_lower("M")) { if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024 * 1024; } if (!to_integer(Tok, Val, 10)) return None; return Val; } ByteCommand *ScriptParser::readByteCommand(StringRef Tok) { int Size = StringSwitch(Tok) .Case("BYTE", 1) .Case("SHORT", 2) .Case("LONG", 4) .Case("QUAD", 8) .Default(-1); if (Size == -1) return nullptr; return make(readParenExpr(), Size); } StringRef ScriptParser::readParenLiteral() { expect("("); StringRef Tok = next(); expect(")"); return Tok; } static void checkIfExists(OutputSection *Cmd, StringRef Location) { if (Cmd->Location.empty() && Script->ErrorOnMissingSection) error(Location + ": undefined section " + Cmd->Name); } Expr ScriptParser::readPrimary() { if (peek() == "(") return readParenExpr(); if (consume("~")) { Expr E = readPrimary(); return [=] { return ~E().getValue(); }; } if (consume("!")) { Expr E = readPrimary(); return [=] { return !E().getValue(); }; } if (consume("-")) { Expr E = readPrimary(); return [=] { return -E().getValue(); }; } StringRef Tok = next(); std::string Location = getCurrentLocation(); // Built-in functions are parsed here. // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. if (Tok == "ABSOLUTE") { Expr Inner = readParenExpr(); return [=] { ExprValue I = Inner(); I.ForceAbsolute = true; return I; }; } if (Tok == "ADDR") { StringRef Name = readParenLiteral(); OutputSection *Sec = Script->getOrCreateOutputSection(Name); return [=]() -> ExprValue { checkIfExists(Sec, Location); return {Sec, false, 0, Location}; }; } if (Tok == "ALIGN") { expect("("); Expr E = readExpr(); if (consume(")")) { E = checkAlignment(E, Location); return [=] { return alignTo(Script->getDot(), E().getValue()); }; } expect(","); Expr E2 = checkAlignment(readExpr(), Location); expect(")"); return [=] { ExprValue V = E(); V.Alignment = E2().getValue(); return V; }; } if (Tok == "ALIGNOF") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); return [=] { checkIfExists(Cmd, Location); return Cmd->Alignment; }; } if (Tok == "ASSERT") return readAssertExpr(); if (Tok == "CONSTANT") return readConstant(); if (Tok == "DATA_SEGMENT_ALIGN") { expect("("); Expr E = readExpr(); expect(","); readExpr(); expect(")"); return [=] { return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue())); }; } if (Tok == "DATA_SEGMENT_END") { expect("("); expect("."); expect(")"); return [] { return Script->getDot(); }; } if (Tok == "DATA_SEGMENT_RELRO_END") { // GNU linkers implements more complicated logic to handle // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and // just align to the next page boundary for simplicity. expect("("); readExpr(); expect(","); readExpr(); expect(")"); Expr E = getPageSize(); return [=] { return alignTo(Script->getDot(), E().getValue()); }; } if (Tok == "DEFINED") { StringRef Name = readParenLiteral(); return [=] { return Symtab->find(Name) ? 1 : 0; }; } if (Tok == "LENGTH") { StringRef Name = readParenLiteral(); if (Script->MemoryRegions.count(Name) == 0) setError("memory region not defined: " + Name); return [=] { return Script->MemoryRegions[Name]->Length; }; } if (Tok == "LOADADDR") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); return [=] { checkIfExists(Cmd, Location); return Cmd->getLMA(); }; } if (Tok == "ORIGIN") { StringRef Name = readParenLiteral(); if (Script->MemoryRegions.count(Name) == 0) setError("memory region not defined: " + Name); return [=] { return Script->MemoryRegions[Name]->Origin; }; } if (Tok == "SEGMENT_START") { expect("("); skip(); expect(","); Expr E = readExpr(); expect(")"); return [=] { return E(); }; } if (Tok == "SIZEOF") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); // Linker script does not create an output section if its content is empty. // We want to allow SIZEOF(.foo) where .foo is a section which happened to // be empty. return [=] { return Cmd->Size; }; } if (Tok == "SIZEOF_HEADERS") return [=] { return elf::getHeaderSize(); }; // Tok is the dot. if (Tok == ".") return [=] { return Script->getSymbolValue(Tok, Location); }; // Tok is a literal number. if (Optional Val = parseInt(Tok)) return [=] { return *Val; }; // Tok is a symbol name. if (!isValidCIdentifier(Tok)) setError("malformed number: " + Tok); Script->ReferencedSymbols.push_back(Tok); return [=] { return Script->getSymbolValue(Tok, Location); }; } Expr ScriptParser::readTernary(Expr Cond) { Expr L = readExpr(); expect(":"); Expr R = readExpr(); return [=] { return Cond().getValue() ? L() : R(); }; } Expr ScriptParser::readParenExpr() { expect("("); Expr E = readExpr(); expect(")"); return E; } std::vector ScriptParser::readOutputSectionPhdrs() { std::vector Phdrs; while (!errorCount() && peek().startswith(":")) { StringRef Tok = next(); Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1)); } return Phdrs; } // Read a program header type name. The next token must be a // name of a program header type or a constant (e.g. "0x3"). unsigned ScriptParser::readPhdrType() { StringRef Tok = next(); if (Optional Val = parseInt(Tok)) return *Val; unsigned Ret = StringSwitch(Tok) .Case("PT_NULL", PT_NULL) .Case("PT_LOAD", PT_LOAD) .Case("PT_DYNAMIC", PT_DYNAMIC) .Case("PT_INTERP", PT_INTERP) .Case("PT_NOTE", PT_NOTE) .Case("PT_SHLIB", PT_SHLIB) .Case("PT_PHDR", PT_PHDR) .Case("PT_TLS", PT_TLS) .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) .Case("PT_GNU_STACK", PT_GNU_STACK) .Case("PT_GNU_RELRO", PT_GNU_RELRO) .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) .Default(-1); if (Ret == (unsigned)-1) { setError("invalid program header type: " + Tok); return PT_NULL; } return Ret; } // Reads an anonymous version declaration. void ScriptParser::readAnonymousDeclaration() { std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); for (SymbolVersion V : Locals) { if (V.Name == "*") Config->DefaultSymbolVersion = VER_NDX_LOCAL; else Config->VersionScriptLocals.push_back(V); } for (SymbolVersion V : Globals) Config->VersionScriptGlobals.push_back(V); expect(";"); } // Reads a non-anonymous version definition, // e.g. "VerStr { global: foo; bar; local: *; };". void ScriptParser::readVersionDeclaration(StringRef VerStr) { // Read a symbol list. std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); for (SymbolVersion V : Locals) { if (V.Name == "*") Config->DefaultSymbolVersion = VER_NDX_LOCAL; else Config->VersionScriptLocals.push_back(V); } // Create a new version definition and add that to the global symbols. VersionDefinition Ver; Ver.Name = VerStr; Ver.Globals = Globals; // User-defined version number starts from 2 because 0 and 1 are // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively. Ver.Id = Config->VersionDefinitions.size() + 2; Config->VersionDefinitions.push_back(Ver); // Each version may have a parent version. For example, "Ver2" // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" // as a parent. This version hierarchy is, probably against your // instinct, purely for hint; the runtime doesn't care about it // at all. In LLD, we simply ignore it. if (peek() != ";") skip(); expect(";"); } static bool hasWildcard(StringRef S) { return S.find_first_of("?*[") != StringRef::npos; } // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". std::pair, std::vector> ScriptParser::readSymbols() { std::vector Locals; std::vector Globals; std::vector *V = &Globals; while (!errorCount()) { if (consume("}")) break; if (consumeLabel("local")) { V = &Locals; continue; } if (consumeLabel("global")) { V = &Globals; continue; } if (consume("extern")) { std::vector Ext = readVersionExtern(); V->insert(V->end(), Ext.begin(), Ext.end()); } else { StringRef Tok = next(); V->push_back({unquote(Tok), false, hasWildcard(Tok)}); } expect(";"); } return {Locals, Globals}; } // Reads an "extern C++" directive, e.g., // "extern "C++" { ns::*; "f(int, double)"; };" std::vector ScriptParser::readVersionExtern() { StringRef Tok = next(); bool IsCXX = Tok == "\"C++\""; if (!IsCXX && Tok != "\"C\"") setError("Unknown language"); expect("{"); std::vector Ret; while (!errorCount() && peek() != "}") { StringRef Tok = next(); bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok); Ret.push_back({unquote(Tok), IsCXX, HasWildcard}); expect(";"); } expect("}"); return Ret; } uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2, StringRef S3) { if (!consume(S1) && !consume(S2) && !consume(S3)) { setError("expected one of: " + S1 + ", " + S2 + ", or " + S3); return 0; } expect("="); return readExpr()().getValue(); } // Parse the MEMORY command as specified in: // https://sourceware.org/binutils/docs/ld/MEMORY.html // // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... } void ScriptParser::readMemory() { expect("{"); while (!errorCount() && !consume("}")) { StringRef Name = next(); uint32_t Flags = 0; uint32_t NegFlags = 0; if (consume("(")) { std::tie(Flags, NegFlags) = readMemoryAttributes(); expect(")"); } expect(":"); uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o"); expect(","); uint64_t Length = readMemoryAssignment("LENGTH", "len", "l"); // Add the memory region to the region map. if (Script->MemoryRegions.count(Name)) setError("region '" + Name + "' already defined"); MemoryRegion *MR = make(); *MR = {Name, Origin, Length, Flags, NegFlags}; Script->MemoryRegions[Name] = MR; } } // This function parses the attributes used to match against section // flags when placing output sections in a memory region. These flags // are only used when an explicit memory region name is not used. std::pair ScriptParser::readMemoryAttributes() { uint32_t Flags = 0; uint32_t NegFlags = 0; bool Invert = false; for (char C : next().lower()) { uint32_t Flag = 0; if (C == '!') Invert = !Invert; else if (C == 'w') Flag = SHF_WRITE; else if (C == 'x') Flag = SHF_EXECINSTR; else if (C == 'a') Flag = SHF_ALLOC; else if (C != 'r') setError("invalid memory region attribute"); if (Invert) NegFlags |= Flag; else Flags |= Flag; } return {Flags, NegFlags}; } void elf::readLinkerScript(MemoryBufferRef MB) { ScriptParser(MB).readLinkerScript(); } void elf::readVersionScript(MemoryBufferRef MB) { ScriptParser(MB).readVersionScript(); } void elf::readDynamicList(MemoryBufferRef MB) { ScriptParser(MB).readDynamicList(); } void elf::readDefsym(StringRef Name, MemoryBufferRef MB) { ScriptParser(MB).readDefsym(Name); }