1 //===- LinkerScript.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the parser/evaluator of the linker script. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "LinkerScript.h" 15 #include "Config.h" 16 #include "InputSection.h" 17 #include "Memory.h" 18 #include "OutputSections.h" 19 #include "Strings.h" 20 #include "SymbolTable.h" 21 #include "Symbols.h" 22 #include "SyntheticSections.h" 23 #include "Target.h" 24 #include "Threads.h" 25 #include "Writer.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/BinaryFormat/ELF.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/Compression.h" 31 #include "llvm/Support/Endian.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/Path.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <cstddef> 38 #include <cstdint> 39 #include <iterator> 40 #include <limits> 41 #include <string> 42 #include <vector> 43 44 using namespace llvm; 45 using namespace llvm::ELF; 46 using namespace llvm::object; 47 using namespace llvm::support::endian; 48 using namespace lld; 49 using namespace lld::elf; 50 51 LinkerScript *elf::Script; 52 53 uint64_t ExprValue::getValue() const { 54 if (Sec) { 55 if (OutputSection *OS = Sec->getOutputSection()) 56 return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment); 57 error(Loc + ": unable to evaluate expression: input section " + Sec->Name + 58 " has no output section assigned"); 59 } 60 return alignTo(Val, Alignment); 61 } 62 63 uint64_t ExprValue::getSecAddr() const { 64 if (Sec) 65 return Sec->getOffset(0) + Sec->getOutputSection()->Addr; 66 return 0; 67 } 68 69 static SymbolBody *addRegular(SymbolAssignment *Cmd) { 70 Symbol *Sym; 71 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 72 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility, 73 /*CanOmitFromDynSym*/ false, 74 /*File*/ nullptr); 75 Sym->Binding = STB_GLOBAL; 76 ExprValue Value = Cmd->Expression(); 77 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; 78 79 // We want to set symbol values early if we can. This allows us to use symbols 80 // as variables in linker scripts. Doing so allows us to write expressions 81 // like this: `alignment = 16; . = ALIGN(., alignment)` 82 uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0; 83 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility, 84 STT_NOTYPE, SymValue, 0, Sec, nullptr); 85 return Sym->body(); 86 } 87 88 OutputSectionCommand * 89 LinkerScript::createOutputSectionCommand(StringRef Name, StringRef Location) { 90 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name]; 91 OutputSectionCommand *Cmd; 92 if (CmdRef && CmdRef->Location.empty()) { 93 // There was a forward reference. 94 Cmd = CmdRef; 95 } else { 96 Cmd = make<OutputSectionCommand>(Name); 97 if (!CmdRef) 98 CmdRef = Cmd; 99 } 100 Cmd->Location = Location; 101 return Cmd; 102 } 103 104 OutputSectionCommand * 105 LinkerScript::getOrCreateOutputSectionCommand(StringRef Name) { 106 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name]; 107 if (!CmdRef) 108 CmdRef = make<OutputSectionCommand>(Name); 109 return CmdRef; 110 } 111 112 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { 113 uint64_t Val = E().getValue(); 114 if (Val < Dot && InSec) 115 error(Loc + ": unable to move location counter backward for: " + 116 CurAddressState->OutSec->Name); 117 Dot = Val; 118 // Update to location counter means update to section size. 119 if (InSec) 120 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr; 121 } 122 123 // Sets value of a symbol. Two kinds of symbols are processed: synthetic 124 // symbols, whose value is an offset from beginning of section and regular 125 // symbols whose value is absolute. 126 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { 127 if (Cmd->Name == ".") { 128 setDot(Cmd->Expression, Cmd->Location, InSec); 129 return; 130 } 131 132 if (!Cmd->Sym) 133 return; 134 135 auto *Sym = cast<DefinedRegular>(Cmd->Sym); 136 ExprValue V = Cmd->Expression(); 137 if (V.isAbsolute()) { 138 Sym->Value = V.getValue(); 139 } else { 140 Sym->Section = V.Sec; 141 Sym->Value = alignTo(V.Val, V.Alignment); 142 } 143 } 144 145 void LinkerScript::addSymbol(SymbolAssignment *Cmd) { 146 if (Cmd->Name == ".") 147 return; 148 149 // If a symbol was in PROVIDE(), we need to define it only when 150 // it is a referenced undefined symbol. 151 SymbolBody *B = Symtab->find(Cmd->Name); 152 if (Cmd->Provide && (!B || B->isDefined())) 153 return; 154 155 Cmd->Sym = addRegular(Cmd); 156 } 157 158 bool SymbolAssignment::classof(const BaseCommand *C) { 159 return C->Kind == AssignmentKind; 160 } 161 162 bool OutputSectionCommand::classof(const BaseCommand *C) { 163 return C->Kind == OutputSectionKind; 164 } 165 166 // Fill [Buf, Buf + Size) with Filler. 167 // This is used for linker script "=fillexp" command. 168 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) { 169 size_t I = 0; 170 for (; I + 4 < Size; I += 4) 171 memcpy(Buf + I, &Filler, 4); 172 memcpy(Buf + I, &Filler, Size - I); 173 } 174 175 bool InputSectionDescription::classof(const BaseCommand *C) { 176 return C->Kind == InputSectionKind; 177 } 178 179 bool AssertCommand::classof(const BaseCommand *C) { 180 return C->Kind == AssertKind; 181 } 182 183 bool BytesDataCommand::classof(const BaseCommand *C) { 184 return C->Kind == BytesDataKind; 185 } 186 187 static StringRef basename(InputSectionBase *S) { 188 if (S->File) 189 return sys::path::filename(S->File->getName()); 190 return ""; 191 } 192 193 bool LinkerScript::shouldKeep(InputSectionBase *S) { 194 for (InputSectionDescription *ID : Opt.KeptSections) 195 if (ID->FilePat.match(basename(S))) 196 for (SectionPattern &P : ID->SectionPatterns) 197 if (P.SectionPat.match(S->Name)) 198 return true; 199 return false; 200 } 201 202 // If an input string is in the form of "foo.N" where N is a number, 203 // return N. Otherwise, returns 65536, which is one greater than the 204 // lowest priority. 205 static int getPriority(StringRef S) { 206 size_t Pos = S.rfind('.'); 207 if (Pos == StringRef::npos) 208 return 65536; 209 int V; 210 if (!to_integer(S.substr(Pos + 1), V, 10)) 211 return 65536; 212 return V; 213 } 214 215 // A helper function for the SORT() command. 216 static std::function<bool(InputSectionBase *, InputSectionBase *)> 217 getComparator(SortSectionPolicy K) { 218 switch (K) { 219 case SortSectionPolicy::Alignment: 220 return [](InputSectionBase *A, InputSectionBase *B) { 221 // ">" is not a mistake. Sections with larger alignments are placed 222 // before sections with smaller alignments in order to reduce the 223 // amount of padding necessary. This is compatible with GNU. 224 return A->Alignment > B->Alignment; 225 }; 226 case SortSectionPolicy::Name: 227 return [](InputSectionBase *A, InputSectionBase *B) { 228 return A->Name < B->Name; 229 }; 230 case SortSectionPolicy::Priority: 231 return [](InputSectionBase *A, InputSectionBase *B) { 232 return getPriority(A->Name) < getPriority(B->Name); 233 }; 234 default: 235 llvm_unreachable("unknown sort policy"); 236 } 237 } 238 239 // A helper function for the SORT() command. 240 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections, 241 ConstraintKind Kind) { 242 if (Kind == ConstraintKind::NoConstraint) 243 return true; 244 245 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) { 246 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE; 247 }); 248 249 return (IsRW && Kind == ConstraintKind::ReadWrite) || 250 (!IsRW && Kind == ConstraintKind::ReadOnly); 251 } 252 253 static void sortSections(InputSection **Begin, InputSection **End, 254 SortSectionPolicy K) { 255 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 256 std::stable_sort(Begin, End, getComparator(K)); 257 } 258 259 // Compute and remember which sections the InputSectionDescription matches. 260 std::vector<InputSection *> 261 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) { 262 std::vector<InputSection *> Ret; 263 264 // Collects all sections that satisfy constraints of Cmd. 265 for (const SectionPattern &Pat : Cmd->SectionPatterns) { 266 size_t SizeBefore = Ret.size(); 267 268 for (InputSectionBase *Sec : InputSections) { 269 if (Sec->Assigned) 270 continue; 271 272 if (!Sec->Live) { 273 reportDiscarded(Sec); 274 continue; 275 } 276 277 // For -emit-relocs we have to ignore entries like 278 // .rela.dyn : { *(.rela.data) } 279 // which are common because they are in the default bfd script. 280 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 281 continue; 282 283 StringRef Filename = basename(Sec); 284 if (!Cmd->FilePat.match(Filename) || 285 Pat.ExcludedFilePat.match(Filename) || 286 !Pat.SectionPat.match(Sec->Name)) 287 continue; 288 289 Ret.push_back(cast<InputSection>(Sec)); 290 Sec->Assigned = true; 291 } 292 293 // Sort sections as instructed by SORT-family commands and --sort-section 294 // option. Because SORT-family commands can be nested at most two depth 295 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 296 // line option is respected even if a SORT command is given, the exact 297 // behavior we have here is a bit complicated. Here are the rules. 298 // 299 // 1. If two SORT commands are given, --sort-section is ignored. 300 // 2. If one SORT command is given, and if it is not SORT_NONE, 301 // --sort-section is handled as an inner SORT command. 302 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 303 // 4. If no SORT command is given, sort according to --sort-section. 304 InputSection **Begin = Ret.data() + SizeBefore; 305 InputSection **End = Ret.data() + Ret.size(); 306 if (Pat.SortOuter != SortSectionPolicy::None) { 307 if (Pat.SortInner == SortSectionPolicy::Default) 308 sortSections(Begin, End, Config->SortSection); 309 else 310 sortSections(Begin, End, Pat.SortInner); 311 sortSections(Begin, End, Pat.SortOuter); 312 } 313 } 314 return Ret; 315 } 316 317 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) { 318 for (InputSectionBase *S : V) { 319 S->Live = false; 320 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab || 321 S == InX::DynStrTab) 322 error("discarding " + S->Name + " section is not allowed"); 323 discard(S->DependentSections); 324 } 325 } 326 327 std::vector<InputSectionBase *> 328 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) { 329 std::vector<InputSectionBase *> Ret; 330 331 for (BaseCommand *Base : OutCmd.Commands) { 332 auto *Cmd = dyn_cast<InputSectionDescription>(Base); 333 if (!Cmd) 334 continue; 335 336 Cmd->Sections = computeInputSections(Cmd); 337 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); 338 } 339 340 return Ret; 341 } 342 343 void LinkerScript::processCommands(OutputSectionFactory &Factory) { 344 // A symbol can be assigned before any section is mentioned in the linker 345 // script. In an DSO, the symbol values are addresses, so the only important 346 // section values are: 347 // * SHN_UNDEF 348 // * SHN_ABS 349 // * Any value meaning a regular section. 350 // To handle that, create a dummy aether section that fills the void before 351 // the linker scripts switches to another section. It has an index of one 352 // which will map to whatever the first actual section is. 353 Aether = make<OutputSection>("", 0, SHF_ALLOC); 354 Aether->SectionIndex = 1; 355 auto State = make_unique<AddressState>(Opt); 356 // CurAddressState captures the local AddressState and makes it accessible 357 // deliberately. This is needed as there are some cases where we cannot just 358 // thread the current state through to a lambda function created by the 359 // script parser. 360 CurAddressState = State.get(); 361 CurAddressState->OutSec = Aether; 362 Dot = 0; 363 364 for (size_t I = 0; I < Opt.Commands.size(); ++I) { 365 // Handle symbol assignments outside of any output section. 366 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) { 367 addSymbol(Cmd); 368 continue; 369 } 370 371 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) { 372 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd); 373 374 // The output section name `/DISCARD/' is special. 375 // Any input section assigned to it is discarded. 376 if (Cmd->Name == "/DISCARD/") { 377 discard(V); 378 continue; 379 } 380 381 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive 382 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input 383 // sections satisfy a given constraint. If not, a directive is handled 384 // as if it wasn't present from the beginning. 385 // 386 // Because we'll iterate over Commands many more times, the easiest 387 // way to "make it as if it wasn't present" is to just remove it. 388 if (!matchConstraints(V, Cmd->Constraint)) { 389 for (InputSectionBase *S : V) 390 S->Assigned = false; 391 Opt.Commands.erase(Opt.Commands.begin() + I); 392 --I; 393 continue; 394 } 395 396 // A directive may contain symbol definitions like this: 397 // ".foo : { ...; bar = .; }". Handle them. 398 for (BaseCommand *Base : Cmd->Commands) 399 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base)) 400 addSymbol(OutCmd); 401 402 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign 403 // is given, input sections are aligned to that value, whether the 404 // given value is larger or smaller than the original section alignment. 405 if (Cmd->SubalignExpr) { 406 uint32_t Subalign = Cmd->SubalignExpr().getValue(); 407 for (InputSectionBase *S : V) 408 S->Alignment = Subalign; 409 } 410 411 // Add input sections to an output section. 412 for (InputSectionBase *S : V) 413 Factory.addInputSec(S, Cmd->Name, Cmd->Sec); 414 if (OutputSection *Sec = Cmd->Sec) { 415 assert(Sec->SectionIndex == INT_MAX); 416 Sec->SectionIndex = I; 417 if (Cmd->Noload) 418 Sec->Type = SHT_NOBITS; 419 SecToCommand[Sec] = Cmd; 420 } 421 } 422 } 423 CurAddressState = nullptr; 424 } 425 426 void LinkerScript::fabricateDefaultCommands() { 427 std::vector<BaseCommand *> Commands; 428 429 // Define start address 430 uint64_t StartAddr = -1; 431 432 // The Sections with -T<section> have been sorted in order of ascending 433 // address. We must lower StartAddr if the lowest -T<section address> as 434 // calls to setDot() must be monotonically increasing. 435 for (auto &KV : Config->SectionStartMap) 436 StartAddr = std::min(StartAddr, KV.second); 437 438 Commands.push_back(make<SymbolAssignment>( 439 ".", 440 [=] { 441 return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize()); 442 }, 443 "")); 444 445 // For each OutputSection that needs a VA fabricate an OutputSectionCommand 446 // with an InputSectionDescription describing the InputSections 447 for (OutputSection *Sec : OutputSections) { 448 auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>"); 449 OSCmd->Sec = Sec; 450 SecToCommand[Sec] = OSCmd; 451 452 Commands.push_back(OSCmd); 453 if (Sec->Sections.size()) { 454 auto *ISD = make<InputSectionDescription>(""); 455 OSCmd->Commands.push_back(ISD); 456 for (InputSection *ISec : Sec->Sections) { 457 ISD->Sections.push_back(ISec); 458 ISec->Assigned = true; 459 } 460 } 461 } 462 // SECTIONS commands run before other non SECTIONS commands 463 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end()); 464 Opt.Commands = std::move(Commands); 465 } 466 467 // Add sections that didn't match any sections command. 468 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) { 469 unsigned NumCommands = Opt.Commands.size(); 470 for (InputSectionBase *S : InputSections) { 471 if (!S->Live || S->Parent) 472 continue; 473 StringRef Name = getOutputSectionName(S->Name); 474 auto End = Opt.Commands.begin() + NumCommands; 475 auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) { 476 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) 477 return Cmd->Name == Name; 478 return false; 479 }); 480 OutputSectionCommand *Cmd; 481 if (I == End) { 482 Factory.addInputSec(S, Name); 483 OutputSection *Sec = S->getOutputSection(); 484 assert(Sec->SectionIndex == INT_MAX); 485 OutputSectionCommand *&CmdRef = SecToCommand[Sec]; 486 if (!CmdRef) { 487 CmdRef = createOutputSectionCommand(Sec->Name, "<internal>"); 488 CmdRef->Sec = Sec; 489 Opt.Commands.push_back(CmdRef); 490 } 491 Cmd = CmdRef; 492 } else { 493 Cmd = cast<OutputSectionCommand>(*I); 494 Factory.addInputSec(S, Name, Cmd->Sec); 495 if (OutputSection *Sec = Cmd->Sec) { 496 SecToCommand[Sec] = Cmd; 497 unsigned Index = std::distance(Opt.Commands.begin(), I); 498 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index); 499 Sec->SectionIndex = Index; 500 } 501 } 502 auto *ISD = make<InputSectionDescription>(""); 503 ISD->Sections.push_back(cast<InputSection>(S)); 504 Cmd->Commands.push_back(ISD); 505 } 506 } 507 508 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) { 509 bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) && 510 CurAddressState->OutSec->Type == SHT_NOBITS; 511 uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot; 512 Start = alignTo(Start, Align); 513 uint64_t End = Start + Size; 514 515 if (IsTbss) 516 CurAddressState->ThreadBssOffset = End - Dot; 517 else 518 Dot = End; 519 return End; 520 } 521 522 void LinkerScript::output(InputSection *S) { 523 uint64_t Before = advance(0, 1); 524 uint64_t Pos = advance(S->getSize(), S->Alignment); 525 S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr; 526 527 // Update output section size after adding each section. This is so that 528 // SIZEOF works correctly in the case below: 529 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 530 CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr; 531 532 // If there is a memory region associated with this input section, then 533 // place the section in that region and update the region index. 534 if (CurAddressState->MemRegion) { 535 uint64_t &CurOffset = 536 CurAddressState->MemRegionOffset[CurAddressState->MemRegion]; 537 CurOffset += Pos - Before; 538 uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin; 539 if (CurSize > CurAddressState->MemRegion->Length) { 540 uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length; 541 error("section '" + CurAddressState->OutSec->Name + 542 "' will not fit in region '" + CurAddressState->MemRegion->Name + 543 "': overflowed by " + Twine(OverflowAmt) + " bytes"); 544 } 545 } 546 } 547 548 void LinkerScript::switchTo(OutputSection *Sec) { 549 if (CurAddressState->OutSec == Sec) 550 return; 551 552 CurAddressState->OutSec = Sec; 553 CurAddressState->OutSec->Addr = 554 advance(0, CurAddressState->OutSec->Alignment); 555 556 // If neither AT nor AT> is specified for an allocatable section, the linker 557 // will set the LMA such that the difference between VMA and LMA for the 558 // section is the same as the preceding output section in the same region 559 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 560 if (CurAddressState->LMAOffset) 561 CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset(); 562 } 563 564 void LinkerScript::process(BaseCommand &Base) { 565 // This handles the assignments to symbol or to the dot. 566 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) { 567 assignSymbol(Cmd, true); 568 return; 569 } 570 571 // Handle BYTE(), SHORT(), LONG(), or QUAD(). 572 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) { 573 Cmd->Offset = Dot - CurAddressState->OutSec->Addr; 574 Dot += Cmd->Size; 575 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr; 576 return; 577 } 578 579 // Handle ASSERT(). 580 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) { 581 Cmd->Expression(); 582 return; 583 } 584 585 // Handle a single input section description command. 586 // It calculates and assigns the offsets for each section and also 587 // updates the output section size. 588 auto &Cmd = cast<InputSectionDescription>(Base); 589 for (InputSection *Sec : Cmd.Sections) { 590 // We tentatively added all synthetic sections at the beginning and removed 591 // empty ones afterwards (because there is no way to know whether they were 592 // going be empty or not other than actually running linker scripts.) 593 // We need to ignore remains of empty sections. 594 if (auto *S = dyn_cast<SyntheticSection>(Sec)) 595 if (S->empty()) 596 continue; 597 598 if (!Sec->Live) 599 continue; 600 assert(CurAddressState->OutSec == Sec->getParent()); 601 output(Sec); 602 } 603 } 604 605 // This function searches for a memory region to place the given output 606 // section in. If found, a pointer to the appropriate memory region is 607 // returned. Otherwise, a nullptr is returned. 608 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) { 609 // If a memory region name was specified in the output section command, 610 // then try to find that region first. 611 if (!Cmd->MemoryRegionName.empty()) { 612 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName); 613 if (It != Opt.MemoryRegions.end()) 614 return &It->second; 615 error("memory region '" + Cmd->MemoryRegionName + "' not declared"); 616 return nullptr; 617 } 618 619 // If at least one memory region is defined, all sections must 620 // belong to some memory region. Otherwise, we don't need to do 621 // anything for memory regions. 622 if (Opt.MemoryRegions.empty()) 623 return nullptr; 624 625 OutputSection *Sec = Cmd->Sec; 626 // See if a region can be found by matching section flags. 627 for (auto &Pair : Opt.MemoryRegions) { 628 MemoryRegion &M = Pair.second; 629 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0) 630 return &M; 631 } 632 633 // Otherwise, no suitable region was found. 634 if (Sec->Flags & SHF_ALLOC) 635 error("no memory region specified for section '" + Sec->Name + "'"); 636 return nullptr; 637 } 638 639 // This function assigns offsets to input sections and an output section 640 // for a single sections command (e.g. ".text { *(.text); }"). 641 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) { 642 OutputSection *Sec = Cmd->Sec; 643 if (!Sec) 644 return; 645 646 if (!(Sec->Flags & SHF_ALLOC)) 647 Dot = 0; 648 else if (Cmd->AddrExpr) 649 setDot(Cmd->AddrExpr, Cmd->Location, false); 650 651 if (Cmd->LMAExpr) { 652 uint64_t D = Dot; 653 CurAddressState->LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; }; 654 } 655 656 CurAddressState->MemRegion = Cmd->MemRegion; 657 if (CurAddressState->MemRegion) 658 Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion]; 659 switchTo(Sec); 660 661 // We do not support custom layout for compressed debug sectons. 662 // At this point we already know their size and have compressed content. 663 if (CurAddressState->OutSec->Flags & SHF_COMPRESSED) 664 return; 665 666 for (BaseCommand *C : Cmd->Commands) 667 process(*C); 668 } 669 670 void LinkerScript::removeEmptyCommands() { 671 // It is common practice to use very generic linker scripts. So for any 672 // given run some of the output sections in the script will be empty. 673 // We could create corresponding empty output sections, but that would 674 // clutter the output. 675 // We instead remove trivially empty sections. The bfd linker seems even 676 // more aggressive at removing them. 677 auto Pos = std::remove_if( 678 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) { 679 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) 680 return Cmd->Sec == nullptr; 681 return false; 682 }); 683 Opt.Commands.erase(Pos, Opt.Commands.end()); 684 } 685 686 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) { 687 for (BaseCommand *Base : Cmd.Commands) 688 if (!isa<InputSectionDescription>(*Base)) 689 return false; 690 return true; 691 } 692 693 void LinkerScript::adjustSectionsBeforeSorting() { 694 // If the output section contains only symbol assignments, create a 695 // corresponding output section. The bfd linker seems to only create them if 696 // '.' is assigned to, but creating these section should not have any bad 697 // consequeces and gives us a section to put the symbol in. 698 uint64_t Flags = SHF_ALLOC; 699 700 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) { 701 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]); 702 if (!Cmd) 703 continue; 704 if (OutputSection *Sec = Cmd->Sec) { 705 Flags = Sec->Flags; 706 continue; 707 } 708 709 if (isAllSectionDescription(*Cmd)) 710 continue; 711 712 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags); 713 OutSec->SectionIndex = I; 714 Cmd->Sec = OutSec; 715 SecToCommand[OutSec] = Cmd; 716 } 717 } 718 719 void LinkerScript::adjustSectionsAfterSorting() { 720 // Try and find an appropriate memory region to assign offsets in. 721 for (BaseCommand *Base : Opt.Commands) { 722 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) { 723 Cmd->MemRegion = findMemoryRegion(Cmd); 724 // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 725 if (Cmd->AlignExpr && Cmd->Sec) 726 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue()); 727 } 728 } 729 730 // If output section command doesn't specify any segments, 731 // and we haven't previously assigned any section to segment, 732 // then we simply assign section to the very first load segment. 733 // Below is an example of such linker script: 734 // PHDRS { seg PT_LOAD; } 735 // SECTIONS { .aaa : { *(.aaa) } } 736 std::vector<StringRef> DefPhdrs; 737 auto FirstPtLoad = 738 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(), 739 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); 740 if (FirstPtLoad != Opt.PhdrsCommands.end()) 741 DefPhdrs.push_back(FirstPtLoad->Name); 742 743 // Walk the commands and propagate the program headers to commands that don't 744 // explicitly specify them. 745 for (BaseCommand *Base : Opt.Commands) { 746 auto *Cmd = dyn_cast<OutputSectionCommand>(Base); 747 if (!Cmd) 748 continue; 749 750 if (Cmd->Phdrs.empty()) { 751 OutputSection *Sec = Cmd->Sec; 752 // To match the bfd linker script behaviour, only propagate program 753 // headers to sections that are allocated. 754 if (Sec && (Sec->Flags & SHF_ALLOC)) 755 Cmd->Phdrs = DefPhdrs; 756 } else { 757 DefPhdrs = Cmd->Phdrs; 758 } 759 } 760 761 removeEmptyCommands(); 762 } 763 764 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) { 765 uint64_t Min = std::numeric_limits<uint64_t>::max(); 766 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 767 OutputSection *Sec = Cmd->Sec; 768 if (Sec->Flags & SHF_ALLOC) 769 Min = std::min<uint64_t>(Min, Sec->Addr); 770 } 771 772 auto It = llvm::find_if( 773 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); 774 if (It == Phdrs.end()) 775 return; 776 PhdrEntry *FirstPTLoad = *It; 777 778 uint64_t HeaderSize = getHeaderSize(); 779 if (HeaderSize <= Min || Script->hasPhdrsCommands()) { 780 Min = alignDown(Min - HeaderSize, Config->MaxPageSize); 781 Out::ElfHeader->Addr = Min; 782 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; 783 return; 784 } 785 786 assert(FirstPTLoad->First == Out::ElfHeader); 787 OutputSection *ActualFirst = nullptr; 788 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 789 OutputSection *Sec = Cmd->Sec; 790 if (Sec->FirstInPtLoad == Out::ElfHeader) { 791 ActualFirst = Sec; 792 break; 793 } 794 } 795 if (ActualFirst) { 796 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 797 OutputSection *Sec = Cmd->Sec; 798 if (Sec->FirstInPtLoad == Out::ElfHeader) 799 Sec->FirstInPtLoad = ActualFirst; 800 } 801 FirstPTLoad->First = ActualFirst; 802 } else { 803 Phdrs.erase(It); 804 } 805 806 auto PhdrI = llvm::find_if( 807 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); 808 if (PhdrI != Phdrs.end()) 809 Phdrs.erase(PhdrI); 810 } 811 812 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) { 813 for (auto &MRI : Opt.MemoryRegions) { 814 const MemoryRegion *MR = &MRI.second; 815 MemRegionOffset[MR] = MR->Origin; 816 } 817 } 818 819 void LinkerScript::assignAddresses() { 820 // Assign addresses as instructed by linker script SECTIONS sub-commands. 821 Dot = 0; 822 auto State = make_unique<AddressState>(Opt); 823 // CurAddressState captures the local AddressState and makes it accessible 824 // deliberately. This is needed as there are some cases where we cannot just 825 // thread the current state through to a lambda function created by the 826 // script parser. 827 CurAddressState = State.get(); 828 ErrorOnMissingSection = true; 829 switchTo(Aether); 830 831 for (BaseCommand *Base : Opt.Commands) { 832 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 833 assignSymbol(Cmd, false); 834 continue; 835 } 836 837 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) { 838 Cmd->Expression(); 839 continue; 840 } 841 842 auto *Cmd = cast<OutputSectionCommand>(Base); 843 assignOffsets(Cmd); 844 } 845 CurAddressState = nullptr; 846 } 847 848 // Creates program headers as instructed by PHDRS linker script command. 849 std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 850 std::vector<PhdrEntry *> Ret; 851 852 // Process PHDRS and FILEHDR keywords because they are not 853 // real output sections and cannot be added in the following loop. 854 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) { 855 PhdrEntry *Phdr = 856 make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags); 857 858 if (Cmd.HasFilehdr) 859 Phdr->add(Out::ElfHeader); 860 if (Cmd.HasPhdrs) 861 Phdr->add(Out::ProgramHeaders); 862 863 if (Cmd.LMAExpr) { 864 Phdr->p_paddr = Cmd.LMAExpr().getValue(); 865 Phdr->HasLMA = true; 866 } 867 Ret.push_back(Phdr); 868 } 869 870 // Add output sections to program headers. 871 for (OutputSectionCommand *Cmd : OutputSectionCommands) { 872 // Assign headers specified by linker script 873 for (size_t Id : getPhdrIndices(Cmd)) { 874 OutputSection *Sec = Cmd->Sec; 875 Ret[Id]->add(Sec); 876 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX) 877 Ret[Id]->p_flags |= Sec->getPhdrFlags(); 878 } 879 } 880 return Ret; 881 } 882 883 bool LinkerScript::ignoreInterpSection() { 884 // Ignore .interp section in case we have PHDRS specification 885 // and PT_INTERP isn't listed. 886 if (Opt.PhdrsCommands.empty()) 887 return false; 888 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) 889 if (Cmd.Type == PT_INTERP) 890 return false; 891 return true; 892 } 893 894 OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const { 895 auto I = SecToCommand.find(Sec); 896 if (I == SecToCommand.end()) 897 return nullptr; 898 return I->second; 899 } 900 901 void OutputSectionCommand::sort(std::function<int(InputSectionBase *S)> Order) { 902 typedef std::pair<unsigned, InputSection *> Pair; 903 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; 904 905 std::vector<Pair> V; 906 assert(Commands.size() == 1); 907 auto *ISD = cast<InputSectionDescription>(Commands[0]); 908 for (InputSection *S : ISD->Sections) 909 V.push_back({Order(S), S}); 910 std::stable_sort(V.begin(), V.end(), Comp); 911 ISD->Sections.clear(); 912 for (Pair &P : V) 913 ISD->Sections.push_back(P.second); 914 } 915 916 // Returns true if S matches /Filename.?\.o$/. 917 static bool isCrtBeginEnd(StringRef S, StringRef Filename) { 918 if (!S.endswith(".o")) 919 return false; 920 S = S.drop_back(2); 921 if (S.endswith(Filename)) 922 return true; 923 return !S.empty() && S.drop_back().endswith(Filename); 924 } 925 926 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } 927 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } 928 929 // .ctors and .dtors are sorted by this priority from highest to lowest. 930 // 931 // 1. The section was contained in crtbegin (crtbegin contains 932 // some sentinel value in its .ctors and .dtors so that the runtime 933 // can find the beginning of the sections.) 934 // 935 // 2. The section has an optional priority value in the form of ".ctors.N" 936 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, 937 // they are compared as string rather than number. 938 // 939 // 3. The section is just ".ctors" or ".dtors". 940 // 941 // 4. The section was contained in crtend, which contains an end marker. 942 // 943 // In an ideal world, we don't need this function because .init_array and 944 // .ctors are duplicate features (and .init_array is newer.) However, there 945 // are too many real-world use cases of .ctors, so we had no choice to 946 // support that with this rather ad-hoc semantics. 947 static bool compCtors(const InputSection *A, const InputSection *B) { 948 bool BeginA = isCrtbegin(A->File->getName()); 949 bool BeginB = isCrtbegin(B->File->getName()); 950 if (BeginA != BeginB) 951 return BeginA; 952 bool EndA = isCrtend(A->File->getName()); 953 bool EndB = isCrtend(B->File->getName()); 954 if (EndA != EndB) 955 return EndB; 956 StringRef X = A->Name; 957 StringRef Y = B->Name; 958 assert(X.startswith(".ctors") || X.startswith(".dtors")); 959 assert(Y.startswith(".ctors") || Y.startswith(".dtors")); 960 X = X.substr(6); 961 Y = Y.substr(6); 962 if (X.empty() && Y.empty()) 963 return false; 964 return X < Y; 965 } 966 967 // Sorts input sections by the special rules for .ctors and .dtors. 968 // Unfortunately, the rules are different from the one for .{init,fini}_array. 969 // Read the comment above. 970 void OutputSectionCommand::sortCtorsDtors() { 971 assert(Commands.size() == 1); 972 auto *ISD = cast<InputSectionDescription>(Commands[0]); 973 std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors); 974 } 975 976 // Sorts input sections by section name suffixes, so that .foo.N comes 977 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. 978 // We want to keep the original order if the priorities are the same 979 // because the compiler keeps the original initialization order in a 980 // translation unit and we need to respect that. 981 // For more detail, read the section of the GCC's manual about init_priority. 982 void OutputSectionCommand::sortInitFini() { 983 // Sort sections by priority. 984 sort([](InputSectionBase *S) { return getPriority(S->Name); }); 985 } 986 987 uint32_t OutputSectionCommand::getFiller() { 988 if (Filler) 989 return *Filler; 990 if (Sec->Flags & SHF_EXECINSTR) 991 return Target->TrapInstr; 992 return 0; 993 } 994 995 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { 996 if (Size == 1) 997 *Buf = Data; 998 else if (Size == 2) 999 write16(Buf, Data, Config->Endianness); 1000 else if (Size == 4) 1001 write32(Buf, Data, Config->Endianness); 1002 else if (Size == 8) 1003 write64(Buf, Data, Config->Endianness); 1004 else 1005 llvm_unreachable("unsupported Size argument"); 1006 } 1007 1008 static bool compareByFilePosition(InputSection *A, InputSection *B) { 1009 // Synthetic doesn't have link order dependecy, stable_sort will keep it last 1010 if (A->kind() == InputSectionBase::Synthetic || 1011 B->kind() == InputSectionBase::Synthetic) 1012 return false; 1013 InputSection *LA = A->getLinkOrderDep(); 1014 InputSection *LB = B->getLinkOrderDep(); 1015 OutputSection *AOut = LA->getParent(); 1016 OutputSection *BOut = LB->getParent(); 1017 if (AOut != BOut) 1018 return AOut->SectionIndex < BOut->SectionIndex; 1019 return LA->OutSecOff < LB->OutSecOff; 1020 } 1021 1022 template <class ELFT> 1023 static void finalizeShtGroup(OutputSection *OS, 1024 ArrayRef<InputSection *> Sections) { 1025 assert(Config->Relocatable && Sections.size() == 1); 1026 1027 // sh_link field for SHT_GROUP sections should contain the section index of 1028 // the symbol table. 1029 OS->Link = InX::SymTab->getParent()->SectionIndex; 1030 1031 // sh_info then contain index of an entry in symbol table section which 1032 // provides signature of the section group. 1033 ObjFile<ELFT> *Obj = Sections[0]->getFile<ELFT>(); 1034 ArrayRef<SymbolBody *> Symbols = Obj->getSymbols(); 1035 OS->Info = InX::SymTab->getSymbolIndex(Symbols[Sections[0]->Info - 1]); 1036 } 1037 1038 template <class ELFT> void OutputSectionCommand::finalize() { 1039 // Link order may be distributed across several InputSectionDescriptions 1040 // but sort must consider them all at once. 1041 std::vector<InputSection **> ScriptSections; 1042 std::vector<InputSection *> Sections; 1043 for (BaseCommand *Base : Commands) 1044 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) 1045 for (InputSection *&IS : ISD->Sections) { 1046 ScriptSections.push_back(&IS); 1047 Sections.push_back(IS); 1048 } 1049 1050 if ((Sec->Flags & SHF_LINK_ORDER)) { 1051 std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition); 1052 for (int I = 0, N = Sections.size(); I < N; ++I) 1053 *ScriptSections[I] = Sections[I]; 1054 1055 // We must preserve the link order dependency of sections with the 1056 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We 1057 // need to translate the InputSection sh_link to the OutputSection sh_link, 1058 // all InputSections in the OutputSection have the same dependency. 1059 if (auto *D = Sections.front()->getLinkOrderDep()) 1060 Sec->Link = D->getParent()->SectionIndex; 1061 } 1062 1063 uint32_t Type = Sec->Type; 1064 if (Type == SHT_GROUP) { 1065 finalizeShtGroup<ELFT>(Sec, Sections); 1066 return; 1067 } 1068 1069 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL)) 1070 return; 1071 1072 InputSection *First = Sections[0]; 1073 if (isa<SyntheticSection>(First)) 1074 return; 1075 1076 Sec->Link = InX::SymTab->getParent()->SectionIndex; 1077 // sh_info for SHT_REL[A] sections should contain the section header index of 1078 // the section to which the relocation applies. 1079 InputSectionBase *S = First->getRelocatedSection(); 1080 Sec->Info = S->getOutputSection()->SectionIndex; 1081 Sec->Flags |= SHF_INFO_LINK; 1082 } 1083 1084 // Compress section contents if this section contains debug info. 1085 template <class ELFT> void OutputSectionCommand::maybeCompress() { 1086 typedef typename ELFT::Chdr Elf_Chdr; 1087 1088 // Compress only DWARF debug sections. 1089 if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) || 1090 !Name.startswith(".debug_")) 1091 return; 1092 1093 // Create a section header. 1094 Sec->ZDebugHeader.resize(sizeof(Elf_Chdr)); 1095 auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data()); 1096 Hdr->ch_type = ELFCOMPRESS_ZLIB; 1097 Hdr->ch_size = Sec->Size; 1098 Hdr->ch_addralign = Sec->Alignment; 1099 1100 // Write section contents to a temporary buffer and compress it. 1101 std::vector<uint8_t> Buf(Sec->Size); 1102 writeTo<ELFT>(Buf.data()); 1103 if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData)) 1104 fatal("compress failed: " + llvm::toString(std::move(E))); 1105 1106 // Update section headers. 1107 Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size(); 1108 Sec->Flags |= SHF_COMPRESSED; 1109 } 1110 1111 template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) { 1112 if (Sec->Type == SHT_NOBITS) 1113 return; 1114 1115 Sec->Loc = Buf; 1116 1117 // If -compress-debug-section is specified and if this is a debug seciton, 1118 // we've already compressed section contents. If that's the case, 1119 // just write it down. 1120 if (!Sec->CompressedData.empty()) { 1121 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size()); 1122 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(), 1123 Sec->CompressedData.size()); 1124 return; 1125 } 1126 1127 // Write leading padding. 1128 std::vector<InputSection *> Sections; 1129 for (BaseCommand *Cmd : Commands) 1130 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd)) 1131 for (InputSection *IS : ISD->Sections) 1132 if (IS->Live) 1133 Sections.push_back(IS); 1134 uint32_t Filler = getFiller(); 1135 if (Filler) 1136 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler); 1137 1138 parallelForEachN(0, Sections.size(), [=](size_t I) { 1139 InputSection *IS = Sections[I]; 1140 IS->writeTo<ELFT>(Buf); 1141 1142 // Fill gaps between sections. 1143 if (Filler) { 1144 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize(); 1145 uint8_t *End; 1146 if (I + 1 == Sections.size()) 1147 End = Buf + Sec->Size; 1148 else 1149 End = Buf + Sections[I + 1]->OutSecOff; 1150 fill(Start, End - Start, Filler); 1151 } 1152 }); 1153 1154 // Linker scripts may have BYTE()-family commands with which you 1155 // can write arbitrary bytes to the output. Process them if any. 1156 for (BaseCommand *Base : Commands) 1157 if (auto *Data = dyn_cast<BytesDataCommand>(Base)) 1158 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size); 1159 } 1160 1161 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) { 1162 if (S == ".") 1163 return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr, Loc}; 1164 if (SymbolBody *B = Symtab->find(S)) { 1165 if (auto *D = dyn_cast<DefinedRegular>(B)) 1166 return {D->Section, D->Value, Loc}; 1167 if (auto *C = dyn_cast<DefinedCommon>(B)) 1168 return {InX::Common, C->Offset, Loc}; 1169 } 1170 error(Loc + ": symbol not found: " + S); 1171 return 0; 1172 } 1173 1174 bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; } 1175 1176 static const size_t NoPhdr = -1; 1177 1178 // Returns indices of ELF headers containing specific section. Each index is a 1179 // zero based number of ELF header listed within PHDRS {} script block. 1180 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSectionCommand *Cmd) { 1181 std::vector<size_t> Ret; 1182 for (StringRef PhdrName : Cmd->Phdrs) { 1183 size_t Index = getPhdrIndex(Cmd->Location, PhdrName); 1184 if (Index != NoPhdr) 1185 Ret.push_back(Index); 1186 } 1187 return Ret; 1188 } 1189 1190 // Returns the index of the segment named PhdrName if found otherwise 1191 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE' 1192 // (which can be used to explicitly specify that a section isn't assigned to a 1193 // segment) then error. 1194 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) { 1195 size_t I = 0; 1196 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) { 1197 if (Cmd.Name == PhdrName) 1198 return I; 1199 ++I; 1200 } 1201 if (PhdrName != "NONE") 1202 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS"); 1203 return NoPhdr; 1204 } 1205 1206 template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf); 1207 template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf); 1208 template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf); 1209 template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf); 1210 1211 template void OutputSectionCommand::maybeCompress<ELF32LE>(); 1212 template void OutputSectionCommand::maybeCompress<ELF32BE>(); 1213 template void OutputSectionCommand::maybeCompress<ELF64LE>(); 1214 template void OutputSectionCommand::maybeCompress<ELF64BE>(); 1215 1216 template void OutputSectionCommand::finalize<ELF32LE>(); 1217 template void OutputSectionCommand::finalize<ELF32BE>(); 1218 template void OutputSectionCommand::finalize<ELF64LE>(); 1219 template void OutputSectionCommand::finalize<ELF64BE>(); 1220