1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===// 2f7c5fbb1SRui Ueyama // 3f7c5fbb1SRui Ueyama // The LLVM Linker 4f7c5fbb1SRui Ueyama // 5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source 6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details. 7f7c5fbb1SRui Ueyama // 8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===// 9f7c5fbb1SRui Ueyama // 10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script. 11629e0aa5SRui Ueyama // It parses a linker script and write the result to Config or ScriptConfig 12629e0aa5SRui Ueyama // objects. 13629e0aa5SRui Ueyama // 14629e0aa5SRui Ueyama // If SECTIONS command is used, a ScriptConfig contains an AST 15629e0aa5SRui Ueyama // of the command which will later be consumed by createSections() and 16629e0aa5SRui Ueyama // assignAddresses(). 17f7c5fbb1SRui Ueyama // 18f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===// 19f7c5fbb1SRui Ueyama 20717677afSRui Ueyama #include "LinkerScript.h" 21f7c5fbb1SRui Ueyama #include "Config.h" 22f7c5fbb1SRui Ueyama #include "Driver.h" 231ebc8ed7SRui Ueyama #include "InputSection.h" 24652852c5SGeorge Rimar #include "OutputSections.h" 25e77b5bf6SAdhemerval Zanella #include "ScriptParser.h" 2693c9af42SRui Ueyama #include "Strings.h" 27eda81a1bSEugene Leviant #include "Symbols.h" 28f7c5fbb1SRui Ueyama #include "SymbolTable.h" 29467c4d55SEugene Leviant #include "Target.h" 30bbe38602SEugene Leviant #include "Writer.h" 31960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h" 32652852c5SGeorge Rimar #include "llvm/Support/ELF.h" 33f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h" 34f7c5fbb1SRui Ueyama #include "llvm/Support/MemoryBuffer.h" 35f03f3cc1SRui Ueyama #include "llvm/Support/Path.h" 36a47ee68dSRui Ueyama #include "llvm/Support/StringSaver.h" 37f7c5fbb1SRui Ueyama 38f7c5fbb1SRui Ueyama using namespace llvm; 39652852c5SGeorge Rimar using namespace llvm::ELF; 401ebc8ed7SRui Ueyama using namespace llvm::object; 41f7c5fbb1SRui Ueyama using namespace lld; 42e0df00b9SRafael Espindola using namespace lld::elf; 43f7c5fbb1SRui Ueyama 4407320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig; 45717677afSRui Ueyama 46076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) { 47076fe157SGeorge Rimar return C->Kind == AssignmentKind; 48076fe157SGeorge Rimar } 49076fe157SGeorge Rimar 50076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) { 51076fe157SGeorge Rimar return C->Kind == OutputSectionKind; 52076fe157SGeorge Rimar } 53076fe157SGeorge Rimar 54eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) { 55eea3114fSGeorge Rimar return C->Kind == InputSectionKind; 56eea3114fSGeorge Rimar } 57eea3114fSGeorge Rimar 5836a153cdSRui Ueyama template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) { 59eea3114fSGeorge Rimar return !S || !S->Live; 60717677afSRui Ueyama } 61717677afSRui Ueyama 6207320e40SRui Ueyama template <class ELFT> 6307320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) { 648ec77e64SRui Ueyama for (StringRef Pat : Opt.KeptSections) 65722830a5SRui Ueyama if (globMatch(Pat, S->getSectionName())) 668ec77e64SRui Ueyama return true; 678ec77e64SRui Ueyama return false; 68481c2ce6SGeorge Rimar } 69481c2ce6SGeorge Rimar 7063dc6509SRui Ueyama static bool match(ArrayRef<StringRef> Patterns, StringRef S) { 7163dc6509SRui Ueyama for (StringRef Pat : Patterns) 7263dc6509SRui Ueyama if (globMatch(Pat, S)) 73eea3114fSGeorge Rimar return true; 74eea3114fSGeorge Rimar return false; 75eea3114fSGeorge Rimar } 76eea3114fSGeorge Rimar 776b274810SRui Ueyama // Create a vector of (<output section name>, <input section name patterns>). 786b274810SRui Ueyama // For example, if a returned vector contains (".text" (".foo.*" ".bar.*")), 796b274810SRui Ueyama // input sections start with ".foo." or ".bar." should be added to 806b274810SRui Ueyama // ".text" section. 816b274810SRui Ueyama template <class ELFT> 82e7282797SDavide Italiano std::vector<std::pair<StringRef, const InputSectionDescription *>> 836b274810SRui Ueyama LinkerScript<ELFT>::getSectionMap() { 84e7282797SDavide Italiano std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret; 856b274810SRui Ueyama 866b274810SRui Ueyama for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) 876b274810SRui Ueyama if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get())) 886b274810SRui Ueyama for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands) 896b274810SRui Ueyama if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get())) 90e7282797SDavide Italiano Ret.emplace_back(Cmd1->Name, Cmd2); 916b274810SRui Ueyama 926b274810SRui Ueyama return Ret; 936b274810SRui Ueyama } 946b274810SRui Ueyama 950659800eSGeorge Rimar static bool fileMatches(const InputSectionDescription *Desc, 960659800eSGeorge Rimar StringRef Filename) { 970659800eSGeorge Rimar if (!globMatch(Desc->FilePattern, Filename)) 980659800eSGeorge Rimar return false; 990659800eSGeorge Rimar return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename); 1000659800eSGeorge Rimar } 1010659800eSGeorge Rimar 1026b274810SRui Ueyama // Returns input sections filtered by given glob patterns. 1036b274810SRui Ueyama template <class ELFT> 1046b274810SRui Ueyama std::vector<InputSectionBase<ELFT> *> 105ad10c3d8SRui Ueyama LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) { 1060659800eSGeorge Rimar ArrayRef<StringRef> Patterns = I->SectionPatterns; 1076b274810SRui Ueyama std::vector<InputSectionBase<ELFT> *> Ret; 1086b274810SRui Ueyama for (const std::unique_ptr<ObjectFile<ELFT>> &F : 1090659800eSGeorge Rimar Symtab<ELFT>::X->getObjectFiles()) { 1100659800eSGeorge Rimar if (fileMatches(I, sys::path::filename(F->getName()))) 1116b274810SRui Ueyama for (InputSectionBase<ELFT> *S : F->getSections()) 1120659800eSGeorge Rimar if (!isDiscarded(S) && !S->OutSec && 1130659800eSGeorge Rimar match(Patterns, S->getSectionName())) 1146b274810SRui Ueyama Ret.push_back(S); 1150659800eSGeorge Rimar } 1163e6b0277SEugene Leviant 1173e6b0277SEugene Leviant if ((llvm::find(Patterns, "COMMON") != Patterns.end())) 118ad10c3d8SRui Ueyama Ret.push_back(CommonInputSection<ELFT>::X); 1193e6b0277SEugene Leviant 1206b274810SRui Ueyama return Ret; 1216b274810SRui Ueyama } 1226b274810SRui Ueyama 123652852c5SGeorge Rimar template <class ELFT> 124a7f7884dSRui Ueyama std::vector<OutputSectionBase<ELFT> *> 125ad10c3d8SRui Ueyama LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) { 1266b274810SRui Ueyama std::vector<OutputSectionBase<ELFT> *> Ret; 127a7f7884dSRui Ueyama 128e63d81bdSEugene Leviant // Add input section to output section. If there is no output section yet, 129e63d81bdSEugene Leviant // then create it and add to output section list. 1306b274810SRui Ueyama auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) { 131e63d81bdSEugene Leviant OutputSectionBase<ELFT> *Sec; 132e63d81bdSEugene Leviant bool IsNew; 133e63d81bdSEugene Leviant std::tie(Sec, IsNew) = Factory.create(C, Name); 134e63d81bdSEugene Leviant if (IsNew) 1356b274810SRui Ueyama Ret.push_back(Sec); 136e63d81bdSEugene Leviant Sec->addSection(C); 137e63d81bdSEugene Leviant }; 138e63d81bdSEugene Leviant 1396b274810SRui Ueyama for (auto &P : getSectionMap()) { 1406b274810SRui Ueyama StringRef OutputName = P.first; 141e7282797SDavide Italiano const InputSectionDescription *I = P.second; 142ad10c3d8SRui Ueyama for (InputSectionBase<ELFT> *S : getInputSections(I)) { 1436b274810SRui Ueyama if (OutputName == "/DISCARD/") { 144eea3114fSGeorge Rimar S->Live = false; 1456b274810SRui Ueyama reportDiscarded(S); 1466b274810SRui Ueyama continue; 147eea3114fSGeorge Rimar } 1486b274810SRui Ueyama Add(S, OutputName); 149eea3114fSGeorge Rimar } 150eea3114fSGeorge Rimar } 151e63d81bdSEugene Leviant 152e63d81bdSEugene Leviant // Add all other input sections, which are not listed in script. 1536b274810SRui Ueyama for (const std::unique_ptr<ObjectFile<ELFT>> &F : 1546b274810SRui Ueyama Symtab<ELFT>::X->getObjectFiles()) 1556b274810SRui Ueyama for (InputSectionBase<ELFT> *S : F->getSections()) 1566b274810SRui Ueyama if (!isDiscarded(S) && !S->OutSec) 1576b274810SRui Ueyama Add(S, getOutputSectionName(S)); 158e63d81bdSEugene Leviant 1593c291e1aSRui Ueyama // Remove from the output all the sections which did not meet 1603c291e1aSRui Ueyama // the optional constraints. 1616b274810SRui Ueyama return filter(Ret); 1623c291e1aSRui Ueyama } 1633c291e1aSRui Ueyama 1643c291e1aSRui Ueyama // Process ONLY_IF_RO and ONLY_IF_RW. 1653c291e1aSRui Ueyama template <class ELFT> 1663c291e1aSRui Ueyama std::vector<OutputSectionBase<ELFT> *> 1673c291e1aSRui Ueyama LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) { 1683c291e1aSRui Ueyama // In this loop, we remove output sections if they don't satisfy 1693c291e1aSRui Ueyama // requested properties. 1703c291e1aSRui Ueyama for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 1713c291e1aSRui Ueyama auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 1723c291e1aSRui Ueyama if (!Cmd || Cmd->Name == "/DISCARD/") 1733c291e1aSRui Ueyama continue; 1743c291e1aSRui Ueyama 175bfc4a4b7SGeorge Rimar if (Cmd->Constraint == ConstraintKind::NoConstraint) 1763c291e1aSRui Ueyama continue; 177bfc4a4b7SGeorge Rimar 178bfc4a4b7SGeorge Rimar auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) { 179bfc4a4b7SGeorge Rimar return S->getName() == Cmd->Name; 180bfc4a4b7SGeorge Rimar }); 181bfc4a4b7SGeorge Rimar if (It == Sections.end()) 182bfc4a4b7SGeorge Rimar continue; 1833c291e1aSRui Ueyama 1843c291e1aSRui Ueyama OutputSectionBase<ELFT> *Sec = *It; 1853c291e1aSRui Ueyama bool Writable = (Sec->getFlags() & SHF_WRITE); 1863c291e1aSRui Ueyama bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly); 1873c291e1aSRui Ueyama bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite); 1883c291e1aSRui Ueyama 1893c291e1aSRui Ueyama if ((RO && Writable) || (RW && !Writable)) { 1903c291e1aSRui Ueyama Sections.erase(It); 1913c291e1aSRui Ueyama continue; 1923c291e1aSRui Ueyama } 1933c291e1aSRui Ueyama } 1943c291e1aSRui Ueyama return Sections; 195e63d81bdSEugene Leviant } 196e63d81bdSEugene Leviant 197e63d81bdSEugene Leviant template <class ELFT> 19810e576e1SGeorge Rimar void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) { 199708019c4SRui Ueyama uint64_t Val = Cmd->Expression(Dot); 20010e576e1SGeorge Rimar if (Cmd->Name == ".") { 20110e576e1SGeorge Rimar Dot = Val; 202a31c91b1SEugene Leviant } else if (!Cmd->Ignore) { 20310e576e1SGeorge Rimar auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name)); 20410e576e1SGeorge Rimar D->Value = Val; 20510e576e1SGeorge Rimar } 20610e576e1SGeorge Rimar } 20710e576e1SGeorge Rimar 20810e576e1SGeorge Rimar template <class ELFT> 20907320e40SRui Ueyama void LinkerScript<ELFT>::assignAddresses( 210dbbd8b15SGeorge Rimar ArrayRef<OutputSectionBase<ELFT> *> Sections) { 211652852c5SGeorge Rimar // Orphan sections are sections present in the input files which 2127c18c28cSRui Ueyama // are not explicitly placed into the output file by the linker script. 2137c18c28cSRui Ueyama // We place orphan sections at end of file. 2147c18c28cSRui Ueyama // Other linkers places them using some heuristics as described in 215652852c5SGeorge Rimar // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections. 2167c18c28cSRui Ueyama for (OutputSectionBase<ELFT> *Sec : Sections) { 217652852c5SGeorge Rimar StringRef Name = Sec->getName(); 218c3e2a4b0SRui Ueyama if (getSectionIndex(Name) == INT_MAX) 219076fe157SGeorge Rimar Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name)); 220652852c5SGeorge Rimar } 221652852c5SGeorge Rimar 2227c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands. 223c998a8c0SRui Ueyama Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize(); 224467c4d55SEugene Leviant uintX_t MinVA = std::numeric_limits<uintX_t>::max(); 225652852c5SGeorge Rimar uintX_t ThreadBssOffset = 0; 226652852c5SGeorge Rimar 227076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 228076fe157SGeorge Rimar if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) { 22910e576e1SGeorge Rimar dispatchAssignment(Cmd); 23005ef4cffSRui Ueyama continue; 231652852c5SGeorge Rimar } 232652852c5SGeorge Rimar 233fb8978fcSDima Stepanov // Find all the sections with required name. There can be more than 2346ad330acSGeorge Rimar // one section with such name, if the alignment, flags or type 235fb8978fcSDima Stepanov // attribute differs. 236076fe157SGeorge Rimar auto *Cmd = cast<OutputSectionCommand>(Base.get()); 237fb8978fcSDima Stepanov for (OutputSectionBase<ELFT> *Sec : Sections) { 238076fe157SGeorge Rimar if (Sec->getName() != Cmd->Name) 239652852c5SGeorge Rimar continue; 240652852c5SGeorge Rimar 24158e5c4dcSGeorge Rimar if (Cmd->AddrExpr) 24258e5c4dcSGeorge Rimar Dot = Cmd->AddrExpr(Dot); 24358e5c4dcSGeorge Rimar 244630c6179SGeorge Rimar if (Cmd->AlignExpr) 245630c6179SGeorge Rimar Sec->updateAlignment(Cmd->AlignExpr(Dot)); 246630c6179SGeorge Rimar 247652852c5SGeorge Rimar if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) { 248c998a8c0SRui Ueyama uintX_t TVA = Dot + ThreadBssOffset; 249424b4081SRui Ueyama TVA = alignTo(TVA, Sec->getAlignment()); 250652852c5SGeorge Rimar Sec->setVA(TVA); 251c998a8c0SRui Ueyama ThreadBssOffset = TVA - Dot + Sec->getSize(); 252652852c5SGeorge Rimar continue; 253652852c5SGeorge Rimar } 254652852c5SGeorge Rimar 255652852c5SGeorge Rimar if (Sec->getFlags() & SHF_ALLOC) { 256424b4081SRui Ueyama Dot = alignTo(Dot, Sec->getAlignment()); 257c998a8c0SRui Ueyama Sec->setVA(Dot); 258467c4d55SEugene Leviant MinVA = std::min(MinVA, Dot); 259c998a8c0SRui Ueyama Dot += Sec->getSize(); 260652852c5SGeorge Rimar continue; 261652852c5SGeorge Rimar } 262652852c5SGeorge Rimar } 263652852c5SGeorge Rimar } 264467c4d55SEugene Leviant 26564c32d6fSRafael Espindola // ELF and Program headers need to be right before the first section in 266b91e7118SGeorge Rimar // memory. Set their addresses accordingly. 267467c4d55SEugene Leviant MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() - 268467c4d55SEugene Leviant Out<ELFT>::ProgramHeaders->getSize(), 269467c4d55SEugene Leviant Target->PageSize); 270467c4d55SEugene Leviant Out<ELFT>::ElfHeader->setVA(MinVA); 271467c4d55SEugene Leviant Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA); 272fb8978fcSDima Stepanov } 273652852c5SGeorge Rimar 27407320e40SRui Ueyama template <class ELFT> 27574df5c7eSRafael Espindola std::vector<PhdrEntry<ELFT>> 276bbe38602SEugene Leviant LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) { 277edebbdf1SRui Ueyama std::vector<PhdrEntry<ELFT>> Ret; 278bbe38602SEugene Leviant 279bbe38602SEugene Leviant for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) { 280edebbdf1SRui Ueyama Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags); 281edebbdf1SRui Ueyama PhdrEntry<ELFT> &Phdr = Ret.back(); 282bbe38602SEugene Leviant 283bbe38602SEugene Leviant if (Cmd.HasFilehdr) 284adca245fSRui Ueyama Phdr.add(Out<ELFT>::ElfHeader); 285bbe38602SEugene Leviant if (Cmd.HasPhdrs) 286adca245fSRui Ueyama Phdr.add(Out<ELFT>::ProgramHeaders); 287bbe38602SEugene Leviant 288bbe38602SEugene Leviant switch (Cmd.Type) { 289bbe38602SEugene Leviant case PT_INTERP: 290fd03cfd2SRui Ueyama if (Out<ELFT>::Interp) 291adca245fSRui Ueyama Phdr.add(Out<ELFT>::Interp); 292bbe38602SEugene Leviant break; 293bbe38602SEugene Leviant case PT_DYNAMIC: 294bbe38602SEugene Leviant if (isOutputDynamic<ELFT>()) { 2950b113671SRafael Espindola Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags(); 296adca245fSRui Ueyama Phdr.add(Out<ELFT>::Dynamic); 297bbe38602SEugene Leviant } 298bbe38602SEugene Leviant break; 299bbe38602SEugene Leviant case PT_GNU_EH_FRAME: 300bbe38602SEugene Leviant if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) { 3010b113671SRafael Espindola Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags(); 302adca245fSRui Ueyama Phdr.add(Out<ELFT>::EhFrameHdr); 303bbe38602SEugene Leviant } 304bbe38602SEugene Leviant break; 305bbe38602SEugene Leviant } 306bbe38602SEugene Leviant } 307bbe38602SEugene Leviant 308edebbdf1SRui Ueyama PhdrEntry<ELFT> *Load = nullptr; 309edebbdf1SRui Ueyama uintX_t Flags = PF_R; 310bbe38602SEugene Leviant for (OutputSectionBase<ELFT> *Sec : Sections) { 311bbe38602SEugene Leviant if (!(Sec->getFlags() & SHF_ALLOC)) 312bbe38602SEugene Leviant break; 313bbe38602SEugene Leviant 314edebbdf1SRui Ueyama std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName()); 315bbe38602SEugene Leviant if (!PhdrIds.empty()) { 316bbe38602SEugene Leviant // Assign headers specified by linker script 317bbe38602SEugene Leviant for (size_t Id : PhdrIds) { 318edebbdf1SRui Ueyama Ret[Id].add(Sec); 319865bf863SEugene Leviant if (Opt.PhdrsCommands[Id].Flags == UINT_MAX) 3200b113671SRafael Espindola Ret[Id].H.p_flags |= Sec->getPhdrFlags(); 321bbe38602SEugene Leviant } 322bbe38602SEugene Leviant } else { 323bbe38602SEugene Leviant // If we have no load segment or flags've changed then we want new load 324bbe38602SEugene Leviant // segment. 3250b113671SRafael Espindola uintX_t NewFlags = Sec->getPhdrFlags(); 326bbe38602SEugene Leviant if (Load == nullptr || Flags != NewFlags) { 327edebbdf1SRui Ueyama Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags); 328bbe38602SEugene Leviant Flags = NewFlags; 329bbe38602SEugene Leviant } 33018f084ffSRui Ueyama Load->add(Sec); 331bbe38602SEugene Leviant } 332bbe38602SEugene Leviant } 333edebbdf1SRui Ueyama return Ret; 334bbe38602SEugene Leviant } 335bbe38602SEugene Leviant 336bbe38602SEugene Leviant template <class ELFT> 33707320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) { 338f6c3ccefSGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) 339f6c3ccefSGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 340f6c3ccefSGeorge Rimar if (Cmd->Name == Name) 341f6c3ccefSGeorge Rimar return Cmd->Filler; 342e2ee72b5SGeorge Rimar return {}; 343e2ee72b5SGeorge Rimar } 344e2ee72b5SGeorge Rimar 345c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script 346c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they 347c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script, 348c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file. 349076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) { 350f510fa6bSRui Ueyama int I = 0; 351f510fa6bSRui Ueyama for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 352076fe157SGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 353076fe157SGeorge Rimar if (Cmd->Name == Name) 354f510fa6bSRui Ueyama return I; 355f510fa6bSRui Ueyama ++I; 356f510fa6bSRui Ueyama } 357f510fa6bSRui Ueyama return INT_MAX; 35871b26e94SGeorge Rimar } 35971b26e94SGeorge Rimar 36071b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if 36171b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0. 36207320e40SRui Ueyama template <class ELFT> 36307320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) { 364c3e2a4b0SRui Ueyama int I = getSectionIndex(A); 365c3e2a4b0SRui Ueyama int J = getSectionIndex(B); 366c3e2a4b0SRui Ueyama if (I == INT_MAX && J == INT_MAX) 367717677afSRui Ueyama return 0; 368717677afSRui Ueyama return I < J ? -1 : 1; 369717677afSRui Ueyama } 370717677afSRui Ueyama 371076fe157SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() { 372a31c91b1SEugene Leviant for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 373a31c91b1SEugene Leviant auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()); 374a31c91b1SEugene Leviant if (!Cmd || Cmd->Name == ".") 375a31c91b1SEugene Leviant continue; 376a31c91b1SEugene Leviant 3778ab4108dSDavide Italiano SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name); 378373a533aSDavide Italiano // The semantic of PROVIDE is that of introducing a symbol only if 379373a533aSDavide Italiano // it's not defined and there's at least a reference to it. 380373a533aSDavide Italiano if ((!B && !Cmd->Provide) || (B && B->isUndefined())) 381a31c91b1SEugene Leviant Symtab<ELFT>::X->addAbsolute(Cmd->Name, 382a31c91b1SEugene Leviant Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT); 383a31c91b1SEugene Leviant else 384a31c91b1SEugene Leviant // Symbol already exists in symbol table. If it is provided 385a31c91b1SEugene Leviant // then we can't override its value. 386a31c91b1SEugene Leviant Cmd->Ignore = Cmd->Provide; 387a31c91b1SEugene Leviant } 388eda81a1bSEugene Leviant } 389eda81a1bSEugene Leviant 390bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() { 391bbe38602SEugene Leviant return !Opt.PhdrsCommands.empty(); 392bbe38602SEugene Leviant } 393bbe38602SEugene Leviant 394bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified 395bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within 396bbe38602SEugene Leviant // PHDRS {} script block. 397bbe38602SEugene Leviant template <class ELFT> 398edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) { 399076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 400076fe157SGeorge Rimar auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 401edebbdf1SRui Ueyama if (!Cmd || Cmd->Name != SectionName) 40231d842f5SGeorge Rimar continue; 40331d842f5SGeorge Rimar 40429c5a2a9SRui Ueyama std::vector<size_t> Ret; 40529c5a2a9SRui Ueyama for (StringRef PhdrName : Cmd->Phdrs) 40629c5a2a9SRui Ueyama Ret.push_back(getPhdrIndex(PhdrName)); 40729c5a2a9SRui Ueyama return Ret; 408bbe38602SEugene Leviant } 40931d842f5SGeorge Rimar return {}; 41031d842f5SGeorge Rimar } 411bbe38602SEugene Leviant 41229c5a2a9SRui Ueyama template <class ELFT> 41329c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) { 41429c5a2a9SRui Ueyama size_t I = 0; 41529c5a2a9SRui Ueyama for (PhdrsCommand &Cmd : Opt.PhdrsCommands) { 41629c5a2a9SRui Ueyama if (Cmd.Name == PhdrName) 41729c5a2a9SRui Ueyama return I; 41829c5a2a9SRui Ueyama ++I; 41929c5a2a9SRui Ueyama } 42029c5a2a9SRui Ueyama error("section header '" + PhdrName + "' is not listed in PHDRS"); 42129c5a2a9SRui Ueyama return 0; 42229c5a2a9SRui Ueyama } 42329c5a2a9SRui Ueyama 42407320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase { 425c3794e58SGeorge Rimar typedef void (ScriptParser::*Handler)(); 426c3794e58SGeorge Rimar 427f7c5fbb1SRui Ueyama public: 42807320e40SRui Ueyama ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {} 429f23b2320SGeorge Rimar 4304a46539cSRui Ueyama void run(); 431f7c5fbb1SRui Ueyama 432f7c5fbb1SRui Ueyama private: 43352a1509eSRui Ueyama void addFile(StringRef Path); 43452a1509eSRui Ueyama 435f7c5fbb1SRui Ueyama void readAsNeeded(); 43690c5099eSDenis Protivensky void readEntry(); 43783f406cfSGeorge Rimar void readExtern(); 438f7c5fbb1SRui Ueyama void readGroup(); 43931aa1f83SRui Ueyama void readInclude(); 440c3794e58SGeorge Rimar void readNothing() {} 441ee59282bSRui Ueyama void readOutput(); 4429159ce93SDavide Italiano void readOutputArch(); 443f7c5fbb1SRui Ueyama void readOutputFormat(); 444bbe38602SEugene Leviant void readPhdrs(); 44568a39a65SDavide Italiano void readSearchDir(); 4468e3b38abSDenis Protivensky void readSections(); 4478e3b38abSDenis Protivensky 448113cdec9SRui Ueyama SymbolAssignment *readAssignment(StringRef Name); 449eda81a1bSEugene Leviant void readOutputSectionDescription(StringRef OutSec); 450bbe38602SEugene Leviant std::vector<StringRef> readOutputSectionPhdrs(); 4510659800eSGeorge Rimar std::unique_ptr<InputSectionDescription> readInputSectionDescription(); 4520659800eSGeorge Rimar void readInputSectionRules(InputSectionDescription *InCmd, bool Keep); 453bbe38602SEugene Leviant unsigned readPhdrType(); 454a31c91b1SEugene Leviant void readProvide(bool Hidden); 455630c6179SGeorge Rimar void readAlign(OutputSectionCommand *Cmd); 45603fc010eSGeorge Rimar void readSort(); 457708019c4SRui Ueyama 458708019c4SRui Ueyama Expr readExpr(); 459708019c4SRui Ueyama Expr readExpr1(Expr Lhs, int MinPrec); 460708019c4SRui Ueyama Expr readPrimary(); 461708019c4SRui Ueyama Expr readTernary(Expr Cond); 462708019c4SRui Ueyama Expr combine(StringRef Op, Expr Lhs, Expr Rhs); 463f7c5fbb1SRui Ueyama 464c3794e58SGeorge Rimar const static StringMap<Handler> Cmd; 46507320e40SRui Ueyama ScriptConfiguration &Opt = *ScriptConfig; 46607320e40SRui Ueyama StringSaver Saver = {ScriptConfig->Alloc}; 46716b0cc9eSSimon Atanasyan bool IsUnderSysroot; 468f7c5fbb1SRui Ueyama }; 469f7c5fbb1SRui Ueyama 470e0df00b9SRafael Espindola const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = { 471c3794e58SGeorge Rimar {"ENTRY", &ScriptParser::readEntry}, 472c3794e58SGeorge Rimar {"EXTERN", &ScriptParser::readExtern}, 473c3794e58SGeorge Rimar {"GROUP", &ScriptParser::readGroup}, 474c3794e58SGeorge Rimar {"INCLUDE", &ScriptParser::readInclude}, 475c3794e58SGeorge Rimar {"INPUT", &ScriptParser::readGroup}, 476c3794e58SGeorge Rimar {"OUTPUT", &ScriptParser::readOutput}, 477c3794e58SGeorge Rimar {"OUTPUT_ARCH", &ScriptParser::readOutputArch}, 478c3794e58SGeorge Rimar {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat}, 479bbe38602SEugene Leviant {"PHDRS", &ScriptParser::readPhdrs}, 480c3794e58SGeorge Rimar {"SEARCH_DIR", &ScriptParser::readSearchDir}, 481c3794e58SGeorge Rimar {"SECTIONS", &ScriptParser::readSections}, 482c3794e58SGeorge Rimar {";", &ScriptParser::readNothing}}; 483c3794e58SGeorge Rimar 484717677afSRui Ueyama void ScriptParser::run() { 485f7c5fbb1SRui Ueyama while (!atEOF()) { 486f7c5fbb1SRui Ueyama StringRef Tok = next(); 487c3794e58SGeorge Rimar if (Handler Fn = Cmd.lookup(Tok)) 488c3794e58SGeorge Rimar (this->*Fn)(); 489c3794e58SGeorge Rimar else 4905761042dSGeorge Rimar setError("unknown directive: " + Tok); 491f7c5fbb1SRui Ueyama } 492f7c5fbb1SRui Ueyama } 493f7c5fbb1SRui Ueyama 494717677afSRui Ueyama void ScriptParser::addFile(StringRef S) { 49516b0cc9eSSimon Atanasyan if (IsUnderSysroot && S.startswith("/")) { 49616b0cc9eSSimon Atanasyan SmallString<128> Path; 49716b0cc9eSSimon Atanasyan (Config->Sysroot + S).toStringRef(Path); 49816b0cc9eSSimon Atanasyan if (sys::fs::exists(Path)) { 49916b0cc9eSSimon Atanasyan Driver->addFile(Saver.save(Path.str())); 50016b0cc9eSSimon Atanasyan return; 50116b0cc9eSSimon Atanasyan } 50216b0cc9eSSimon Atanasyan } 50316b0cc9eSSimon Atanasyan 504f03f3cc1SRui Ueyama if (sys::path::is_absolute(S)) { 50552a1509eSRui Ueyama Driver->addFile(S); 50652a1509eSRui Ueyama } else if (S.startswith("=")) { 50752a1509eSRui Ueyama if (Config->Sysroot.empty()) 50852a1509eSRui Ueyama Driver->addFile(S.substr(1)); 50952a1509eSRui Ueyama else 51052a1509eSRui Ueyama Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1))); 51152a1509eSRui Ueyama } else if (S.startswith("-l")) { 51221eecb4fSRui Ueyama Driver->addLibrary(S.substr(2)); 513a1b8fc3bSSimon Atanasyan } else if (sys::fs::exists(S)) { 514a1b8fc3bSSimon Atanasyan Driver->addFile(S); 51552a1509eSRui Ueyama } else { 51652a1509eSRui Ueyama std::string Path = findFromSearchPaths(S); 51752a1509eSRui Ueyama if (Path.empty()) 518777f9630SGeorge Rimar setError("unable to find " + S); 519025d59b1SRui Ueyama else 52052a1509eSRui Ueyama Driver->addFile(Saver.save(Path)); 52152a1509eSRui Ueyama } 52252a1509eSRui Ueyama } 52352a1509eSRui Ueyama 524717677afSRui Ueyama void ScriptParser::readAsNeeded() { 525f7c5fbb1SRui Ueyama expect("("); 52635da9b6eSRui Ueyama bool Orig = Config->AsNeeded; 52735da9b6eSRui Ueyama Config->AsNeeded = true; 528025d59b1SRui Ueyama while (!Error) { 529f7c5fbb1SRui Ueyama StringRef Tok = next(); 530f7c5fbb1SRui Ueyama if (Tok == ")") 53135da9b6eSRui Ueyama break; 53252a1509eSRui Ueyama addFile(Tok); 533f7c5fbb1SRui Ueyama } 53435da9b6eSRui Ueyama Config->AsNeeded = Orig; 535f7c5fbb1SRui Ueyama } 536f7c5fbb1SRui Ueyama 537717677afSRui Ueyama void ScriptParser::readEntry() { 53890c5099eSDenis Protivensky // -e <symbol> takes predecence over ENTRY(<symbol>). 53990c5099eSDenis Protivensky expect("("); 54090c5099eSDenis Protivensky StringRef Tok = next(); 54190c5099eSDenis Protivensky if (Config->Entry.empty()) 54290c5099eSDenis Protivensky Config->Entry = Tok; 54390c5099eSDenis Protivensky expect(")"); 54490c5099eSDenis Protivensky } 54590c5099eSDenis Protivensky 546717677afSRui Ueyama void ScriptParser::readExtern() { 54783f406cfSGeorge Rimar expect("("); 548025d59b1SRui Ueyama while (!Error) { 54983f406cfSGeorge Rimar StringRef Tok = next(); 55083f406cfSGeorge Rimar if (Tok == ")") 55183f406cfSGeorge Rimar return; 55283f406cfSGeorge Rimar Config->Undefined.push_back(Tok); 55383f406cfSGeorge Rimar } 55483f406cfSGeorge Rimar } 55583f406cfSGeorge Rimar 556717677afSRui Ueyama void ScriptParser::readGroup() { 557f7c5fbb1SRui Ueyama expect("("); 558025d59b1SRui Ueyama while (!Error) { 559f7c5fbb1SRui Ueyama StringRef Tok = next(); 560f7c5fbb1SRui Ueyama if (Tok == ")") 561f7c5fbb1SRui Ueyama return; 562f7c5fbb1SRui Ueyama if (Tok == "AS_NEEDED") { 563f7c5fbb1SRui Ueyama readAsNeeded(); 564f7c5fbb1SRui Ueyama continue; 565f7c5fbb1SRui Ueyama } 56652a1509eSRui Ueyama addFile(Tok); 567f7c5fbb1SRui Ueyama } 568f7c5fbb1SRui Ueyama } 569f7c5fbb1SRui Ueyama 570717677afSRui Ueyama void ScriptParser::readInclude() { 57131aa1f83SRui Ueyama StringRef Tok = next(); 57231aa1f83SRui Ueyama auto MBOrErr = MemoryBuffer::getFile(Tok); 573025d59b1SRui Ueyama if (!MBOrErr) { 5745761042dSGeorge Rimar setError("cannot open " + Tok); 575025d59b1SRui Ueyama return; 576025d59b1SRui Ueyama } 57731aa1f83SRui Ueyama std::unique_ptr<MemoryBuffer> &MB = *MBOrErr; 578a47ee68dSRui Ueyama StringRef S = Saver.save(MB->getMemBufferRef().getBuffer()); 579a47ee68dSRui Ueyama std::vector<StringRef> V = tokenize(S); 58031aa1f83SRui Ueyama Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end()); 58131aa1f83SRui Ueyama } 58231aa1f83SRui Ueyama 583717677afSRui Ueyama void ScriptParser::readOutput() { 584ee59282bSRui Ueyama // -o <file> takes predecence over OUTPUT(<file>). 585ee59282bSRui Ueyama expect("("); 586ee59282bSRui Ueyama StringRef Tok = next(); 587ee59282bSRui Ueyama if (Config->OutputFile.empty()) 588ee59282bSRui Ueyama Config->OutputFile = Tok; 589ee59282bSRui Ueyama expect(")"); 590ee59282bSRui Ueyama } 591ee59282bSRui Ueyama 592717677afSRui Ueyama void ScriptParser::readOutputArch() { 5939159ce93SDavide Italiano // Error checking only for now. 5949159ce93SDavide Italiano expect("("); 5959159ce93SDavide Italiano next(); 5969159ce93SDavide Italiano expect(")"); 5979159ce93SDavide Italiano } 5989159ce93SDavide Italiano 599717677afSRui Ueyama void ScriptParser::readOutputFormat() { 600f7c5fbb1SRui Ueyama // Error checking only for now. 601f7c5fbb1SRui Ueyama expect("("); 602f7c5fbb1SRui Ueyama next(); 6036836c618SDavide Italiano StringRef Tok = next(); 6046836c618SDavide Italiano if (Tok == ")") 6056836c618SDavide Italiano return; 606025d59b1SRui Ueyama if (Tok != ",") { 6075761042dSGeorge Rimar setError("unexpected token: " + Tok); 608025d59b1SRui Ueyama return; 609025d59b1SRui Ueyama } 6106836c618SDavide Italiano next(); 6116836c618SDavide Italiano expect(","); 6126836c618SDavide Italiano next(); 613f7c5fbb1SRui Ueyama expect(")"); 614f7c5fbb1SRui Ueyama } 615f7c5fbb1SRui Ueyama 616bbe38602SEugene Leviant void ScriptParser::readPhdrs() { 617bbe38602SEugene Leviant expect("{"); 618bbe38602SEugene Leviant while (!Error && !skip("}")) { 619bbe38602SEugene Leviant StringRef Tok = next(); 620865bf863SEugene Leviant Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX}); 621bbe38602SEugene Leviant PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back(); 622bbe38602SEugene Leviant 623bbe38602SEugene Leviant PhdrCmd.Type = readPhdrType(); 624bbe38602SEugene Leviant do { 625bbe38602SEugene Leviant Tok = next(); 626bbe38602SEugene Leviant if (Tok == ";") 627bbe38602SEugene Leviant break; 628bbe38602SEugene Leviant if (Tok == "FILEHDR") 629bbe38602SEugene Leviant PhdrCmd.HasFilehdr = true; 630bbe38602SEugene Leviant else if (Tok == "PHDRS") 631bbe38602SEugene Leviant PhdrCmd.HasPhdrs = true; 632865bf863SEugene Leviant else if (Tok == "FLAGS") { 633865bf863SEugene Leviant expect("("); 634865bf863SEugene Leviant next().getAsInteger(0, PhdrCmd.Flags); 635865bf863SEugene Leviant expect(")"); 636865bf863SEugene Leviant } else 637bbe38602SEugene Leviant setError("unexpected header attribute: " + Tok); 638bbe38602SEugene Leviant } while (!Error); 639bbe38602SEugene Leviant } 640bbe38602SEugene Leviant } 641bbe38602SEugene Leviant 642717677afSRui Ueyama void ScriptParser::readSearchDir() { 64368a39a65SDavide Italiano expect("("); 64406501920SRafael Espindola Config->SearchPaths.push_back(next()); 64568a39a65SDavide Italiano expect(")"); 64668a39a65SDavide Italiano } 64768a39a65SDavide Italiano 648717677afSRui Ueyama void ScriptParser::readSections() { 64907320e40SRui Ueyama Opt.DoLayout = true; 6508e3b38abSDenis Protivensky expect("{"); 651652852c5SGeorge Rimar while (!Error && !skip("}")) { 652113cdec9SRui Ueyama StringRef Tok = next(); 65330835ea4SGeorge Rimar if (peek() == "=" || peek() == "+=") { 654113cdec9SRui Ueyama readAssignment(Tok); 655113cdec9SRui Ueyama expect(";"); 656113cdec9SRui Ueyama } else if (Tok == "PROVIDE") { 657a31c91b1SEugene Leviant readProvide(false); 658708019c4SRui Ueyama } else if (Tok == "PROVIDE_HIDDEN") { 659a31c91b1SEugene Leviant readProvide(true); 660708019c4SRui Ueyama } else { 661eda81a1bSEugene Leviant readOutputSectionDescription(Tok); 6628e3b38abSDenis Protivensky } 663652852c5SGeorge Rimar } 664708019c4SRui Ueyama } 6658e3b38abSDenis Protivensky 666708019c4SRui Ueyama static int precedence(StringRef Op) { 667708019c4SRui Ueyama return StringSwitch<int>(Op) 668708019c4SRui Ueyama .Case("*", 4) 669708019c4SRui Ueyama .Case("/", 4) 670708019c4SRui Ueyama .Case("+", 3) 671708019c4SRui Ueyama .Case("-", 3) 672708019c4SRui Ueyama .Case("<", 2) 673708019c4SRui Ueyama .Case(">", 2) 674708019c4SRui Ueyama .Case(">=", 2) 675708019c4SRui Ueyama .Case("<=", 2) 676708019c4SRui Ueyama .Case("==", 2) 677708019c4SRui Ueyama .Case("!=", 2) 678708019c4SRui Ueyama .Case("&", 1) 679708019c4SRui Ueyama .Default(-1); 680708019c4SRui Ueyama } 681708019c4SRui Ueyama 6820659800eSGeorge Rimar void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd, bool Keep) { 6830659800eSGeorge Rimar InCmd->FilePattern = next(); 6840ed42b0cSDavide Italiano expect("("); 685e7282797SDavide Italiano 686e7282797SDavide Italiano if (skip("EXCLUDE_FILE")) { 687e7282797SDavide Italiano expect("("); 688e7282797SDavide Italiano while (!Error && !skip(")")) 689e7282797SDavide Italiano InCmd->ExcludedFiles.push_back(next()); 690e7282797SDavide Italiano } 691e7282797SDavide Italiano 6920659800eSGeorge Rimar while (!Error && !skip(")")) { 6930659800eSGeorge Rimar if (Keep) 6940659800eSGeorge Rimar Opt.KeptSections.push_back(peek()); 6950659800eSGeorge Rimar InCmd->SectionPatterns.push_back(next()); 6960659800eSGeorge Rimar } 6970659800eSGeorge Rimar } 6980659800eSGeorge Rimar 6990659800eSGeorge Rimar std::unique_ptr<InputSectionDescription> 7000659800eSGeorge Rimar ScriptParser::readInputSectionDescription() { 701352eac37SGeorge Rimar auto InCmd = llvm::make_unique<InputSectionDescription>(); 7020659800eSGeorge Rimar 7030659800eSGeorge Rimar // Input section wildcard can be surrounded by KEEP. 7040659800eSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 7050659800eSGeorge Rimar if (skip("KEEP")) { 706e7282797SDavide Italiano expect("("); 7070659800eSGeorge Rimar readInputSectionRules(InCmd.get(), true); 7080ed42b0cSDavide Italiano expect(")"); 7090659800eSGeorge Rimar } else { 7100659800eSGeorge Rimar readInputSectionRules(InCmd.get(), false); 7110659800eSGeorge Rimar } 7120659800eSGeorge Rimar 7130659800eSGeorge Rimar return InCmd; 7140ed42b0cSDavide Italiano } 7150ed42b0cSDavide Italiano 716630c6179SGeorge Rimar void ScriptParser::readAlign(OutputSectionCommand *Cmd) { 717630c6179SGeorge Rimar expect("("); 718630c6179SGeorge Rimar Cmd->AlignExpr = readExpr(); 719630c6179SGeorge Rimar expect(")"); 720630c6179SGeorge Rimar } 721630c6179SGeorge Rimar 72203fc010eSGeorge Rimar void ScriptParser::readSort() { 72303fc010eSGeorge Rimar expect("("); 72403fc010eSGeorge Rimar expect("CONSTRUCTORS"); 72503fc010eSGeorge Rimar expect(")"); 72603fc010eSGeorge Rimar } 72703fc010eSGeorge Rimar 728eda81a1bSEugene Leviant void ScriptParser::readOutputSectionDescription(StringRef OutSec) { 729076fe157SGeorge Rimar OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec); 730076fe157SGeorge Rimar Opt.Commands.emplace_back(Cmd); 73158e5c4dcSGeorge Rimar 73258e5c4dcSGeorge Rimar // Read an address expression. 73358e5c4dcSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address 73458e5c4dcSGeorge Rimar if (peek() != ":") 73558e5c4dcSGeorge Rimar Cmd->AddrExpr = readExpr(); 73658e5c4dcSGeorge Rimar 7378e3b38abSDenis Protivensky expect(":"); 738246f681eSDavide Italiano 739630c6179SGeorge Rimar if (skip("ALIGN")) 740630c6179SGeorge Rimar readAlign(Cmd); 741630c6179SGeorge Rimar 742246f681eSDavide Italiano // Parse constraints. 743246f681eSDavide Italiano if (skip("ONLY_IF_RO")) 744efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadOnly; 745246f681eSDavide Italiano if (skip("ONLY_IF_RW")) 746efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadWrite; 7478e3b38abSDenis Protivensky expect("{"); 7488ec77e64SRui Ueyama 749025d59b1SRui Ueyama while (!Error && !skip("}")) { 750*f586ff7eSGeorge Rimar if (peek().startswith("*") || peek() == "KEEP") { 7510659800eSGeorge Rimar Cmd->Commands.push_back(readInputSectionDescription()); 7520659800eSGeorge Rimar continue; 7530659800eSGeorge Rimar } 7540659800eSGeorge Rimar 755481c2ce6SGeorge Rimar StringRef Tok = next(); 7560659800eSGeorge Rimar if (Tok == "PROVIDE") { 757054a6796SDavide Italiano readProvide(false); 758054a6796SDavide Italiano } else if (Tok == "PROVIDE_HIDDEN") { 759054a6796SDavide Italiano readProvide(true); 76003fc010eSGeorge Rimar } else if (Tok == "SORT") { 76103fc010eSGeorge Rimar readSort(); 762481c2ce6SGeorge Rimar } else { 763777f9630SGeorge Rimar setError("unknown command " + Tok); 764481c2ce6SGeorge Rimar } 7658e3b38abSDenis Protivensky } 766076fe157SGeorge Rimar Cmd->Phdrs = readOutputSectionPhdrs(); 7678ec77e64SRui Ueyama 768e2ee72b5SGeorge Rimar StringRef Tok = peek(); 769e2ee72b5SGeorge Rimar if (Tok.startswith("=")) { 770e2ee72b5SGeorge Rimar if (!Tok.startswith("=0x")) { 7713ed2f069SRui Ueyama setError("filler should be a hexadecimal value"); 772e2ee72b5SGeorge Rimar return; 773e2ee72b5SGeorge Rimar } 7743e808976SRui Ueyama Tok = Tok.substr(3); 775f6c3ccefSGeorge Rimar Cmd->Filler = parseHex(Tok); 776e2ee72b5SGeorge Rimar next(); 777e2ee72b5SGeorge Rimar } 7788e3b38abSDenis Protivensky } 7798e3b38abSDenis Protivensky 780a31c91b1SEugene Leviant void ScriptParser::readProvide(bool Hidden) { 781a31c91b1SEugene Leviant expect("("); 782113cdec9SRui Ueyama if (SymbolAssignment *Assignment = readAssignment(next())) { 783a31c91b1SEugene Leviant Assignment->Provide = true; 784a31c91b1SEugene Leviant Assignment->Hidden = Hidden; 785a31c91b1SEugene Leviant } 786a31c91b1SEugene Leviant expect(")"); 787a31c91b1SEugene Leviant expect(";"); 788eda81a1bSEugene Leviant } 789eda81a1bSEugene Leviant 79030835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) { 79130835ea4SGeorge Rimar if (S == ".") 79230835ea4SGeorge Rimar return Dot; 793a31c91b1SEugene Leviant 794a9c5a528SGeorge Rimar switch (Config->EKind) { 795a9c5a528SGeorge Rimar case ELF32LEKind: 796a9c5a528SGeorge Rimar if (SymbolBody *B = Symtab<ELF32LE>::X->find(S)) 797a9c5a528SGeorge Rimar return B->getVA<ELF32LE>(); 798a9c5a528SGeorge Rimar break; 799a9c5a528SGeorge Rimar case ELF32BEKind: 800a9c5a528SGeorge Rimar if (SymbolBody *B = Symtab<ELF32BE>::X->find(S)) 801a9c5a528SGeorge Rimar return B->getVA<ELF32BE>(); 802a9c5a528SGeorge Rimar break; 803a9c5a528SGeorge Rimar case ELF64LEKind: 804a9c5a528SGeorge Rimar if (SymbolBody *B = Symtab<ELF64LE>::X->find(S)) 805a9c5a528SGeorge Rimar return B->getVA<ELF64LE>(); 806a9c5a528SGeorge Rimar break; 807a9c5a528SGeorge Rimar case ELF64BEKind: 808a9c5a528SGeorge Rimar if (SymbolBody *B = Symtab<ELF64BE>::X->find(S)) 809a9c5a528SGeorge Rimar return B->getVA<ELF64BE>(); 810a9c5a528SGeorge Rimar break; 8116930a6dcSGeorge Rimar default: 812b567b628SGeorge Rimar llvm_unreachable("unsupported target"); 813a9c5a528SGeorge Rimar } 814a9c5a528SGeorge Rimar error("symbol not found: " + S); 815a9c5a528SGeorge Rimar return 0; 816a9c5a528SGeorge Rimar } 817a9c5a528SGeorge Rimar 81830835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) { 81930835ea4SGeorge Rimar StringRef Op = next(); 82030835ea4SGeorge Rimar assert(Op == "=" || Op == "+="); 82130835ea4SGeorge Rimar Expr E = readExpr(); 82230835ea4SGeorge Rimar if (Op == "+=") 82330835ea4SGeorge Rimar E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); }; 82430835ea4SGeorge Rimar auto *Cmd = new SymbolAssignment(Name, E); 82530835ea4SGeorge Rimar Opt.Commands.emplace_back(Cmd); 82630835ea4SGeorge Rimar return Cmd; 82730835ea4SGeorge Rimar } 82830835ea4SGeorge Rimar 82930835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker 83030835ea4SGeorge Rimar // script expression. 83130835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); } 83230835ea4SGeorge Rimar 833708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function 834708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator. 835708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { 836708019c4SRui Ueyama while (!atEOF() && !Error) { 837708019c4SRui Ueyama // Read an operator and an expression. 838708019c4SRui Ueyama StringRef Op1 = peek(); 839708019c4SRui Ueyama if (Op1 == "?") 840708019c4SRui Ueyama return readTernary(Lhs); 841708019c4SRui Ueyama if (precedence(Op1) < MinPrec) 842a31c91b1SEugene Leviant break; 843a31c91b1SEugene Leviant next(); 844708019c4SRui Ueyama Expr Rhs = readPrimary(); 845708019c4SRui Ueyama 846708019c4SRui Ueyama // Evaluate the remaining part of the expression first if the 847708019c4SRui Ueyama // next operator has greater precedence than the previous one. 848708019c4SRui Ueyama // For example, if we have read "+" and "3", and if the next 849708019c4SRui Ueyama // operator is "*", then we'll evaluate 3 * ... part first. 850708019c4SRui Ueyama while (!atEOF()) { 851708019c4SRui Ueyama StringRef Op2 = peek(); 852708019c4SRui Ueyama if (precedence(Op2) <= precedence(Op1)) 853eda81a1bSEugene Leviant break; 854708019c4SRui Ueyama Rhs = readExpr1(Rhs, precedence(Op2)); 855eda81a1bSEugene Leviant } 856708019c4SRui Ueyama 857708019c4SRui Ueyama Lhs = combine(Op1, Lhs, Rhs); 858708019c4SRui Ueyama } 859708019c4SRui Ueyama return Lhs; 860708019c4SRui Ueyama } 861708019c4SRui Ueyama 862708019c4SRui Ueyama uint64_t static getConstant(StringRef S) { 863708019c4SRui Ueyama if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE") 864708019c4SRui Ueyama return Target->PageSize; 865708019c4SRui Ueyama error("unknown constant: " + S); 866708019c4SRui Ueyama return 0; 867708019c4SRui Ueyama } 868708019c4SRui Ueyama 869708019c4SRui Ueyama Expr ScriptParser::readPrimary() { 870708019c4SRui Ueyama StringRef Tok = next(); 871708019c4SRui Ueyama 872708019c4SRui Ueyama if (Tok == "(") { 873708019c4SRui Ueyama Expr E = readExpr(); 874708019c4SRui Ueyama expect(")"); 875708019c4SRui Ueyama return E; 876708019c4SRui Ueyama } 877708019c4SRui Ueyama 878708019c4SRui Ueyama // Built-in functions are parsed here. 879708019c4SRui Ueyama // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 880708019c4SRui Ueyama if (Tok == "ALIGN") { 881708019c4SRui Ueyama expect("("); 882708019c4SRui Ueyama Expr E = readExpr(); 883708019c4SRui Ueyama expect(")"); 884708019c4SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 885708019c4SRui Ueyama } 886708019c4SRui Ueyama if (Tok == "CONSTANT") { 887708019c4SRui Ueyama expect("("); 888708019c4SRui Ueyama StringRef Tok = next(); 889708019c4SRui Ueyama expect(")"); 890708019c4SRui Ueyama return [=](uint64_t Dot) { return getConstant(Tok); }; 891708019c4SRui Ueyama } 89254c145ceSRafael Espindola if (Tok == "SEGMENT_START") { 89354c145ceSRafael Espindola expect("("); 89454c145ceSRafael Espindola next(); 89554c145ceSRafael Espindola expect(","); 89654c145ceSRafael Espindola uint64_t Val; 89754c145ceSRafael Espindola next().getAsInteger(0, Val); 89854c145ceSRafael Espindola expect(")"); 89954c145ceSRafael Espindola return [=](uint64_t Dot) { return Val; }; 90054c145ceSRafael Espindola } 901708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_ALIGN") { 902708019c4SRui Ueyama expect("("); 903708019c4SRui Ueyama Expr E = readExpr(); 904708019c4SRui Ueyama expect(","); 905708019c4SRui Ueyama readExpr(); 906708019c4SRui Ueyama expect(")"); 907f7791bb9SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 908708019c4SRui Ueyama } 909708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_END") { 910708019c4SRui Ueyama expect("("); 911708019c4SRui Ueyama expect("."); 912708019c4SRui Ueyama expect(")"); 913708019c4SRui Ueyama return [](uint64_t Dot) { return Dot; }; 914708019c4SRui Ueyama } 915276b4e64SGeorge Rimar // GNU linkers implements more complicated logic to handle 916276b4e64SGeorge Rimar // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to 917276b4e64SGeorge Rimar // the next page boundary for simplicity. 918276b4e64SGeorge Rimar if (Tok == "DATA_SEGMENT_RELRO_END") { 919276b4e64SGeorge Rimar expect("("); 920276b4e64SGeorge Rimar next(); 921276b4e64SGeorge Rimar expect(","); 922276b4e64SGeorge Rimar readExpr(); 923276b4e64SGeorge Rimar expect(")"); 924276b4e64SGeorge Rimar return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); }; 925276b4e64SGeorge Rimar } 926708019c4SRui Ueyama 927a9c5a528SGeorge Rimar // Parse a symbol name or a number literal. 928708019c4SRui Ueyama uint64_t V = 0; 929a9c5a528SGeorge Rimar if (Tok.getAsInteger(0, V)) { 93030835ea4SGeorge Rimar if (Tok != "." && !isValidCIdentifier(Tok)) 931708019c4SRui Ueyama setError("malformed number: " + Tok); 93230835ea4SGeorge Rimar return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); }; 933a9c5a528SGeorge Rimar } 934708019c4SRui Ueyama return [=](uint64_t Dot) { return V; }; 935708019c4SRui Ueyama } 936708019c4SRui Ueyama 937708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) { 938708019c4SRui Ueyama next(); 939708019c4SRui Ueyama Expr L = readExpr(); 940708019c4SRui Ueyama expect(":"); 941708019c4SRui Ueyama Expr R = readExpr(); 942708019c4SRui Ueyama return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); }; 943708019c4SRui Ueyama } 944708019c4SRui Ueyama 945708019c4SRui Ueyama Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) { 946708019c4SRui Ueyama if (Op == "*") 947708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) * R(Dot); }; 948708019c4SRui Ueyama if (Op == "/") { 949708019c4SRui Ueyama return [=](uint64_t Dot) -> uint64_t { 950708019c4SRui Ueyama uint64_t RHS = R(Dot); 951708019c4SRui Ueyama if (RHS == 0) { 952708019c4SRui Ueyama error("division by zero"); 953708019c4SRui Ueyama return 0; 954708019c4SRui Ueyama } 955708019c4SRui Ueyama return L(Dot) / RHS; 956708019c4SRui Ueyama }; 957708019c4SRui Ueyama } 958708019c4SRui Ueyama if (Op == "+") 959708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) + R(Dot); }; 960708019c4SRui Ueyama if (Op == "-") 961708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) - R(Dot); }; 962708019c4SRui Ueyama if (Op == "<") 963708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) < R(Dot); }; 964708019c4SRui Ueyama if (Op == ">") 965708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) > R(Dot); }; 966708019c4SRui Ueyama if (Op == ">=") 967708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) >= R(Dot); }; 968708019c4SRui Ueyama if (Op == "<=") 969708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) <= R(Dot); }; 970708019c4SRui Ueyama if (Op == "==") 971708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) == R(Dot); }; 972708019c4SRui Ueyama if (Op == "!=") 973708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) != R(Dot); }; 974708019c4SRui Ueyama if (Op == "&") 975708019c4SRui Ueyama return [=](uint64_t Dot) { return L(Dot) & R(Dot); }; 976708019c4SRui Ueyama llvm_unreachable("invalid operator"); 977eda81a1bSEugene Leviant } 978eda81a1bSEugene Leviant 979bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() { 980bbe38602SEugene Leviant std::vector<StringRef> Phdrs; 981bbe38602SEugene Leviant while (!Error && peek().startswith(":")) { 982bbe38602SEugene Leviant StringRef Tok = next(); 983bbe38602SEugene Leviant Tok = (Tok.size() == 1) ? next() : Tok.substr(1); 984bbe38602SEugene Leviant if (Tok.empty()) { 985bbe38602SEugene Leviant setError("section header name is empty"); 986bbe38602SEugene Leviant break; 987bbe38602SEugene Leviant } 988bbe38602SEugene Leviant Phdrs.push_back(Tok); 989bbe38602SEugene Leviant } 990bbe38602SEugene Leviant return Phdrs; 991bbe38602SEugene Leviant } 992bbe38602SEugene Leviant 993bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() { 994bbe38602SEugene Leviant StringRef Tok = next(); 995b0f6c590SRui Ueyama unsigned Ret = StringSwitch<unsigned>(Tok) 996b0f6c590SRui Ueyama .Case("PT_NULL", PT_NULL) 997b0f6c590SRui Ueyama .Case("PT_LOAD", PT_LOAD) 998b0f6c590SRui Ueyama .Case("PT_DYNAMIC", PT_DYNAMIC) 999b0f6c590SRui Ueyama .Case("PT_INTERP", PT_INTERP) 1000b0f6c590SRui Ueyama .Case("PT_NOTE", PT_NOTE) 1001b0f6c590SRui Ueyama .Case("PT_SHLIB", PT_SHLIB) 1002b0f6c590SRui Ueyama .Case("PT_PHDR", PT_PHDR) 1003b0f6c590SRui Ueyama .Case("PT_TLS", PT_TLS) 1004b0f6c590SRui Ueyama .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 1005b0f6c590SRui Ueyama .Case("PT_GNU_STACK", PT_GNU_STACK) 1006b0f6c590SRui Ueyama .Case("PT_GNU_RELRO", PT_GNU_RELRO) 1007b0f6c590SRui Ueyama .Default(-1); 1008bbe38602SEugene Leviant 1009b0f6c590SRui Ueyama if (Ret == (unsigned)-1) { 1010b0f6c590SRui Ueyama setError("invalid program header type: " + Tok); 1011b0f6c590SRui Ueyama return PT_NULL; 1012b0f6c590SRui Ueyama } 1013b0f6c590SRui Ueyama return Ret; 1014bbe38602SEugene Leviant } 1015bbe38602SEugene Leviant 101616b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) { 101716b0cc9eSSimon Atanasyan if (Config->Sysroot == "") 101816b0cc9eSSimon Atanasyan return false; 101916b0cc9eSSimon Atanasyan for (; !Path.empty(); Path = sys::path::parent_path(Path)) 102016b0cc9eSSimon Atanasyan if (sys::fs::equivalent(Config->Sysroot, Path)) 102116b0cc9eSSimon Atanasyan return true; 102216b0cc9eSSimon Atanasyan return false; 102316b0cc9eSSimon Atanasyan } 102416b0cc9eSSimon Atanasyan 102507320e40SRui Ueyama // Entry point. 102607320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) { 102716b0cc9eSSimon Atanasyan StringRef Path = MB.getBufferIdentifier(); 102807320e40SRui Ueyama ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run(); 1029f7c5fbb1SRui Ueyama } 10301ebc8ed7SRui Ueyama 103107320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>; 103207320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>; 103307320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>; 103407320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>; 1035