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 "Writer.h" 25 #include "lld/Common/Threads.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/Endian.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/Path.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstddef> 37 #include <cstdint> 38 #include <iterator> 39 #include <limits> 40 #include <string> 41 #include <vector> 42 43 using namespace llvm; 44 using namespace llvm::ELF; 45 using namespace llvm::object; 46 using namespace llvm::support::endian; 47 using namespace lld; 48 using namespace lld::elf; 49 50 LinkerScript *elf::Script; 51 52 static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) { 53 if (OutputSection *OS = InputSec->getOutputSection()) 54 return OS->Addr; 55 error(Loc + ": unable to evaluate expression: input section " + 56 InputSec->Name + " has no output section assigned"); 57 return 0; 58 } 59 60 uint64_t ExprValue::getValue() const { 61 if (Sec) 62 return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc), 63 Alignment); 64 return alignTo(Val, Alignment); 65 } 66 67 uint64_t ExprValue::getSecAddr() const { 68 if (Sec) 69 return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc); 70 return 0; 71 } 72 73 uint64_t ExprValue::getSectionOffset() const { 74 // If the alignment is trivial, we don't have to compute the full 75 // value to know the offset. This allows this function to succeed in 76 // cases where the output section is not yet known. 77 if (Alignment == 1) 78 return Val; 79 return getValue() - getSecAddr(); 80 } 81 82 OutputSection *LinkerScript::createOutputSection(StringRef Name, 83 StringRef Location) { 84 OutputSection *&SecRef = NameToOutputSection[Name]; 85 OutputSection *Sec; 86 if (SecRef && SecRef->Location.empty()) { 87 // There was a forward reference. 88 Sec = SecRef; 89 } else { 90 Sec = make<OutputSection>(Name, SHT_PROGBITS, 0); 91 if (!SecRef) 92 SecRef = Sec; 93 } 94 Sec->Location = Location; 95 return Sec; 96 } 97 98 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) { 99 OutputSection *&CmdRef = NameToOutputSection[Name]; 100 if (!CmdRef) 101 CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0); 102 return CmdRef; 103 } 104 105 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { 106 uint64_t Val = E().getValue(); 107 if (Val < Dot && InSec) 108 error(Loc + ": unable to move location counter backward for: " + 109 Ctx->OutSec->Name); 110 Dot = Val; 111 112 // Update to location counter means update to section size. 113 if (InSec) 114 Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; 115 } 116 117 // This function is called from processSectionCommands, 118 // while we are fixing the output section layout. 119 void LinkerScript::addSymbol(SymbolAssignment *Cmd) { 120 if (Cmd->Name == ".") 121 return; 122 123 // If a symbol was in PROVIDE(), we need to define it only when 124 // it is a referenced undefined symbol. 125 SymbolBody *B = Symtab->find(Cmd->Name); 126 if (Cmd->Provide && (!B || B->isDefined())) 127 return; 128 129 // Define a symbol. 130 Symbol *Sym; 131 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 132 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility, 133 /*CanOmitFromDynSym*/ false, 134 /*File*/ nullptr); 135 Sym->Binding = STB_GLOBAL; 136 ExprValue Value = Cmd->Expression(); 137 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; 138 139 // When this function is called, section addresses have not been 140 // fixed yet. So, we may or may not know the value of the RHS 141 // expression. 142 // 143 // For example, if an expression is `x = 42`, we know x is always 42. 144 // However, if an expression is `x = .`, there's no way to know its 145 // value at the moment. 146 // 147 // We want to set symbol values early if we can. This allows us to 148 // use symbols as variables in linker scripts. Doing so allows us to 149 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`. 150 uint64_t SymValue = Value.Sec ? 0 : Value.getValue(); 151 152 replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false, 153 Visibility, STT_NOTYPE, SymValue, 0, Sec); 154 Cmd->Sym = cast<DefinedRegular>(Sym->body()); 155 } 156 157 // This function is called from assignAddresses, while we are 158 // fixing the output section addresses. This function is supposed 159 // to set the final value for a given symbol assignment. 160 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { 161 if (Cmd->Name == ".") { 162 setDot(Cmd->Expression, Cmd->Location, InSec); 163 return; 164 } 165 166 if (!Cmd->Sym) 167 return; 168 169 ExprValue V = Cmd->Expression(); 170 if (V.isAbsolute()) { 171 Cmd->Sym->Section = nullptr; 172 Cmd->Sym->Value = V.getValue(); 173 } else { 174 Cmd->Sym->Section = V.Sec; 175 Cmd->Sym->Value = V.getSectionOffset(); 176 } 177 } 178 179 static std::string getFilename(InputFile *File) { 180 if (!File) 181 return ""; 182 if (File->ArchiveName.empty()) 183 return File->getName(); 184 return (File->ArchiveName + "(" + File->getName() + ")").str(); 185 } 186 187 bool LinkerScript::shouldKeep(InputSectionBase *S) { 188 std::string Filename = getFilename(S->File); 189 for (InputSectionDescription *ID : KeptSections) 190 if (ID->FilePat.match(Filename)) 191 for (SectionPattern &P : ID->SectionPatterns) 192 if (P.SectionPat.match(S->Name)) 193 return true; 194 return false; 195 } 196 197 // A helper function for the SORT() command. 198 static std::function<bool(InputSectionBase *, InputSectionBase *)> 199 getComparator(SortSectionPolicy K) { 200 switch (K) { 201 case SortSectionPolicy::Alignment: 202 return [](InputSectionBase *A, InputSectionBase *B) { 203 // ">" is not a mistake. Sections with larger alignments are placed 204 // before sections with smaller alignments in order to reduce the 205 // amount of padding necessary. This is compatible with GNU. 206 return A->Alignment > B->Alignment; 207 }; 208 case SortSectionPolicy::Name: 209 return [](InputSectionBase *A, InputSectionBase *B) { 210 return A->Name < B->Name; 211 }; 212 case SortSectionPolicy::Priority: 213 return [](InputSectionBase *A, InputSectionBase *B) { 214 return getPriority(A->Name) < getPriority(B->Name); 215 }; 216 default: 217 llvm_unreachable("unknown sort policy"); 218 } 219 } 220 221 // A helper function for the SORT() command. 222 static bool matchConstraints(ArrayRef<InputSection *> Sections, 223 ConstraintKind Kind) { 224 if (Kind == ConstraintKind::NoConstraint) 225 return true; 226 227 bool IsRW = llvm::any_of( 228 Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; }); 229 230 return (IsRW && Kind == ConstraintKind::ReadWrite) || 231 (!IsRW && Kind == ConstraintKind::ReadOnly); 232 } 233 234 static void sortSections(MutableArrayRef<InputSection *> Vec, 235 SortSectionPolicy K) { 236 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 237 std::stable_sort(Vec.begin(), Vec.end(), getComparator(K)); 238 } 239 240 // Sort sections as instructed by SORT-family commands and --sort-section 241 // option. Because SORT-family commands can be nested at most two depth 242 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 243 // line option is respected even if a SORT command is given, the exact 244 // behavior we have here is a bit complicated. Here are the rules. 245 // 246 // 1. If two SORT commands are given, --sort-section is ignored. 247 // 2. If one SORT command is given, and if it is not SORT_NONE, 248 // --sort-section is handled as an inner SORT command. 249 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 250 // 4. If no SORT command is given, sort according to --sort-section. 251 // 5. If no SORT commands are given and --sort-section is not specified, 252 // apply sorting provided by --symbol-ordering-file if any exist. 253 static void sortInputSections( 254 MutableArrayRef<InputSection *> Vec, const SectionPattern &Pat, 255 const DenseMap<SectionBase *, int> &Order) { 256 if (Pat.SortOuter == SortSectionPolicy::None) 257 return; 258 259 if (Pat.SortOuter == SortSectionPolicy::Default && 260 Config->SortSection == SortSectionPolicy::Default) { 261 // If -symbol-ordering-file was given, sort accordingly. 262 // Usually, Order is empty. 263 if (!Order.empty()) 264 sortByOrder(Vec, [&](InputSectionBase *S) { return Order.lookup(S); }); 265 return; 266 } 267 268 if (Pat.SortInner == SortSectionPolicy::Default) 269 sortSections(Vec, Config->SortSection); 270 else 271 sortSections(Vec, Pat.SortInner); 272 sortSections(Vec, Pat.SortOuter); 273 } 274 275 // Compute and remember which sections the InputSectionDescription matches. 276 std::vector<InputSection *> 277 LinkerScript::computeInputSections(const InputSectionDescription *Cmd, 278 const DenseMap<SectionBase *, int> &Order) { 279 std::vector<InputSection *> Ret; 280 281 // Collects all sections that satisfy constraints of Cmd. 282 for (const SectionPattern &Pat : Cmd->SectionPatterns) { 283 size_t SizeBefore = Ret.size(); 284 285 for (InputSectionBase *Sec : InputSections) { 286 if (Sec->Assigned) 287 continue; 288 289 if (!Sec->Live) { 290 reportDiscarded(Sec); 291 continue; 292 } 293 294 // For -emit-relocs we have to ignore entries like 295 // .rela.dyn : { *(.rela.data) } 296 // which are common because they are in the default bfd script. 297 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 298 continue; 299 300 std::string Filename = getFilename(Sec->File); 301 if (!Cmd->FilePat.match(Filename) || 302 Pat.ExcludedFilePat.match(Filename) || 303 !Pat.SectionPat.match(Sec->Name)) 304 continue; 305 306 // It is safe to assume that Sec is an InputSection 307 // because mergeable or EH input sections have already been 308 // handled and eliminated. 309 Ret.push_back(cast<InputSection>(Sec)); 310 Sec->Assigned = true; 311 } 312 313 sortInputSections(MutableArrayRef<InputSection *>(Ret).slice(SizeBefore), 314 Pat, Order); 315 } 316 return Ret; 317 } 318 319 void LinkerScript::discard(ArrayRef<InputSection *> V) { 320 for (InputSection *S : V) { 321 S->Live = false; 322 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab || 323 S == InX::DynStrTab) 324 error("discarding " + S->Name + " section is not allowed"); 325 discard(S->DependentSections); 326 } 327 } 328 329 std::vector<InputSection *> LinkerScript::createInputSectionList( 330 OutputSection &OutCmd, const DenseMap<SectionBase *, int> &Order) { 331 std::vector<InputSection *> Ret; 332 333 for (BaseCommand *Base : OutCmd.SectionCommands) { 334 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) { 335 Cmd->Sections = computeInputSections(Cmd, Order); 336 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); 337 } 338 } 339 return Ret; 340 } 341 342 void LinkerScript::processSectionCommands() { 343 // A symbol can be assigned before any section is mentioned in the linker 344 // script. In an DSO, the symbol values are addresses, so the only important 345 // section values are: 346 // * SHN_UNDEF 347 // * SHN_ABS 348 // * Any value meaning a regular section. 349 // To handle that, create a dummy aether section that fills the void before 350 // the linker scripts switches to another section. It has an index of one 351 // which will map to whatever the first actual section is. 352 Aether = make<OutputSection>("", 0, SHF_ALLOC); 353 Aether->SectionIndex = 1; 354 355 // Ctx captures the local AddressState and makes it accessible deliberately. 356 // This is needed as there are some cases where we cannot just 357 // thread the current state through to a lambda function created by the 358 // script parser. 359 Ctx = make_unique<AddressState>(); 360 Ctx->OutSec = Aether; 361 362 DenseMap<SectionBase *, int> Order = buildSectionOrder(); 363 // Add input sections to output sections. 364 for (size_t I = 0; I < SectionCommands.size(); ++I) { 365 // Handle symbol assignments outside of any output section. 366 if (auto *Cmd = dyn_cast<SymbolAssignment>(SectionCommands[I])) { 367 addSymbol(Cmd); 368 continue; 369 } 370 371 if (auto *Sec = dyn_cast<OutputSection>(SectionCommands[I])) { 372 std::vector<InputSection *> V = createInputSectionList(*Sec, Order); 373 374 // The output section name `/DISCARD/' is special. 375 // Any input section assigned to it is discarded. 376 if (Sec->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 SectionCommands 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, Sec->Constraint)) { 389 for (InputSectionBase *S : V) 390 S->Assigned = false; 391 SectionCommands.erase(SectionCommands.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 : Sec->SectionCommands) 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 (Sec->SubalignExpr) { 406 uint32_t Subalign = Sec->SubalignExpr().getValue(); 407 for (InputSectionBase *S : V) 408 S->Alignment = Subalign; 409 } 410 411 // Add input sections to an output section. 412 for (InputSection *S : V) 413 Sec->addSection(S); 414 } 415 } 416 Ctx = nullptr; 417 418 // Output sections are emitted in the exact same order as 419 // appeared in SECTIONS command, so we know their section indices. 420 for (size_t I = 0; I < SectionCommands.size(); ++I) { 421 auto *Sec = dyn_cast<OutputSection>(SectionCommands[I]); 422 if (!Sec) 423 continue; 424 assert(Sec->SectionIndex == INT_MAX); 425 Sec->SectionIndex = I; 426 if (Sec->Noload) 427 Sec->Type = SHT_NOBITS; 428 } 429 } 430 431 // If no SECTIONS command was given, we create simple SectionCommands 432 // as if a minimum SECTIONS command were given. This function does that. 433 void LinkerScript::fabricateDefaultCommands() { 434 // Define start address 435 uint64_t StartAddr = UINT64_MAX; 436 437 // The Sections with -T<section> have been sorted in order of ascending 438 // address. We must lower StartAddr if the lowest -T<section address> as 439 // calls to setDot() must be monotonically increasing. 440 for (auto &KV : Config->SectionStartMap) 441 StartAddr = std::min(StartAddr, KV.second); 442 443 auto Expr = [=] { 444 return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize()); 445 }; 446 SectionCommands.insert(SectionCommands.begin(), 447 make<SymbolAssignment>(".", Expr, "")); 448 } 449 450 static OutputSection *findByName(ArrayRef<BaseCommand *> Vec, 451 StringRef Name) { 452 for (BaseCommand *Base : Vec) 453 if (auto *Sec = dyn_cast<OutputSection>(Base)) 454 if (Sec->Name == Name) 455 return Sec; 456 return nullptr; 457 } 458 459 // Add sections that didn't match any sections command. 460 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) { 461 unsigned End = SectionCommands.size(); 462 463 for (InputSectionBase *S : InputSections) { 464 if (!S->Live || S->Parent) 465 continue; 466 467 StringRef Name = getOutputSectionName(S->Name); 468 log(toString(S) + " is being placed in '" + Name + "'"); 469 470 if (OutputSection *Sec = 471 findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) { 472 Sec->addSection(cast<InputSection>(S)); 473 continue; 474 } 475 476 if (OutputSection *OS = Factory.addInputSec(S, Name)) 477 SectionCommands.push_back(OS); 478 assert(S->getOutputSection()->SectionIndex == INT_MAX); 479 } 480 } 481 482 uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) { 483 bool IsTbss = 484 (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS; 485 uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot; 486 Start = alignTo(Start, Alignment); 487 uint64_t End = Start + Size; 488 489 if (IsTbss) 490 Ctx->ThreadBssOffset = End - Dot; 491 else 492 Dot = End; 493 return End; 494 } 495 496 void LinkerScript::output(InputSection *S) { 497 uint64_t Before = advance(0, 1); 498 uint64_t Pos = advance(S->getSize(), S->Alignment); 499 S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr; 500 501 // Update output section size after adding each section. This is so that 502 // SIZEOF works correctly in the case below: 503 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 504 Ctx->OutSec->Size = Pos - Ctx->OutSec->Addr; 505 506 // If there is a memory region associated with this input section, then 507 // place the section in that region and update the region index. 508 if (Ctx->MemRegion) { 509 uint64_t &CurOffset = Ctx->MemRegionOffset[Ctx->MemRegion]; 510 CurOffset += Pos - Before; 511 uint64_t CurSize = CurOffset - Ctx->MemRegion->Origin; 512 if (CurSize > Ctx->MemRegion->Length) { 513 uint64_t OverflowAmt = CurSize - Ctx->MemRegion->Length; 514 error("section '" + Ctx->OutSec->Name + "' will not fit in region '" + 515 Ctx->MemRegion->Name + "': overflowed by " + Twine(OverflowAmt) + 516 " bytes"); 517 } 518 } 519 } 520 521 void LinkerScript::switchTo(OutputSection *Sec) { 522 if (Ctx->OutSec == Sec) 523 return; 524 525 Ctx->OutSec = Sec; 526 Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment); 527 528 // If neither AT nor AT> is specified for an allocatable section, the linker 529 // will set the LMA such that the difference between VMA and LMA for the 530 // section is the same as the preceding output section in the same region 531 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 532 if (Ctx->LMAOffset) 533 Ctx->OutSec->LMAOffset = Ctx->LMAOffset(); 534 } 535 536 // This function searches for a memory region to place the given output 537 // section in. If found, a pointer to the appropriate memory region is 538 // returned. Otherwise, a nullptr is returned. 539 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) { 540 // If a memory region name was specified in the output section command, 541 // then try to find that region first. 542 if (!Sec->MemoryRegionName.empty()) { 543 auto It = MemoryRegions.find(Sec->MemoryRegionName); 544 if (It != MemoryRegions.end()) 545 return It->second; 546 error("memory region '" + Sec->MemoryRegionName + "' not declared"); 547 return nullptr; 548 } 549 550 // If at least one memory region is defined, all sections must 551 // belong to some memory region. Otherwise, we don't need to do 552 // anything for memory regions. 553 if (MemoryRegions.empty()) 554 return nullptr; 555 556 // See if a region can be found by matching section flags. 557 for (auto &Pair : MemoryRegions) { 558 MemoryRegion *M = Pair.second; 559 if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0) 560 return M; 561 } 562 563 // Otherwise, no suitable region was found. 564 if (Sec->Flags & SHF_ALLOC) 565 error("no memory region specified for section '" + Sec->Name + "'"); 566 return nullptr; 567 } 568 569 // This function assigns offsets to input sections and an output section 570 // for a single sections command (e.g. ".text { *(.text); }"). 571 void LinkerScript::assignOffsets(OutputSection *Sec) { 572 if (!(Sec->Flags & SHF_ALLOC)) 573 Dot = 0; 574 else if (Sec->AddrExpr) 575 setDot(Sec->AddrExpr, Sec->Location, false); 576 577 Ctx->MemRegion = Sec->MemRegion; 578 if (Ctx->MemRegion) 579 Dot = Ctx->MemRegionOffset[Ctx->MemRegion]; 580 581 if (Sec->LMAExpr) { 582 uint64_t D = Dot; 583 Ctx->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; }; 584 } 585 586 switchTo(Sec); 587 588 // We do not support custom layout for compressed debug sectons. 589 // At this point we already know their size and have compressed content. 590 if (Ctx->OutSec->Flags & SHF_COMPRESSED) 591 return; 592 593 // We visited SectionsCommands from processSectionCommands to 594 // layout sections. Now, we visit SectionsCommands again to fix 595 // section offsets. 596 for (BaseCommand *Base : Sec->SectionCommands) { 597 // This handles the assignments to symbol or to the dot. 598 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 599 assignSymbol(Cmd, true); 600 continue; 601 } 602 603 // Handle BYTE(), SHORT(), LONG(), or QUAD(). 604 if (auto *Cmd = dyn_cast<ByteCommand>(Base)) { 605 Cmd->Offset = Dot - Ctx->OutSec->Addr; 606 Dot += Cmd->Size; 607 Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; 608 continue; 609 } 610 611 // Handle ASSERT(). 612 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) { 613 Cmd->Expression(); 614 continue; 615 } 616 617 // Handle a single input section description command. 618 // It calculates and assigns the offsets for each section and also 619 // updates the output section size. 620 auto *Cmd = cast<InputSectionDescription>(Base); 621 for (InputSection *Sec : Cmd->Sections) { 622 // We tentatively added all synthetic sections at the beginning and 623 // removed empty ones afterwards (because there is no way to know 624 // whether they were going be empty or not other than actually running 625 // linker scripts.) We need to ignore remains of empty sections. 626 if (auto *S = dyn_cast<SyntheticSection>(Sec)) 627 if (S->empty()) 628 continue; 629 630 if (!Sec->Live) 631 continue; 632 assert(Ctx->OutSec == Sec->getParent()); 633 output(Sec); 634 } 635 } 636 } 637 638 void LinkerScript::removeEmptyCommands() { 639 // It is common practice to use very generic linker scripts. So for any 640 // given run some of the output sections in the script will be empty. 641 // We could create corresponding empty output sections, but that would 642 // clutter the output. 643 // We instead remove trivially empty sections. The bfd linker seems even 644 // more aggressive at removing them. 645 llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { 646 if (auto *Sec = dyn_cast<OutputSection>(Base)) 647 return !Sec->Live; 648 return false; 649 }); 650 } 651 652 static bool isAllSectionDescription(const OutputSection &Cmd) { 653 for (BaseCommand *Base : Cmd.SectionCommands) 654 if (!isa<InputSectionDescription>(*Base)) 655 return false; 656 return true; 657 } 658 659 void LinkerScript::adjustSectionsBeforeSorting() { 660 // If the output section contains only symbol assignments, create a 661 // corresponding output section. The issue is what to do with linker script 662 // like ".foo : { symbol = 42; }". One option would be to convert it to 663 // "symbol = 42;". That is, move the symbol out of the empty section 664 // description. That seems to be what bfd does for this simple case. The 665 // problem is that this is not completely general. bfd will give up and 666 // create a dummy section too if there is a ". = . + 1" inside the section 667 // for example. 668 // Given that we want to create the section, we have to worry what impact 669 // it will have on the link. For example, if we just create a section with 670 // 0 for flags, it would change which PT_LOADs are created. 671 // We could remember that that particular section is dummy and ignore it in 672 // other parts of the linker, but unfortunately there are quite a few places 673 // that would need to change: 674 // * The program header creation. 675 // * The orphan section placement. 676 // * The address assignment. 677 // The other option is to pick flags that minimize the impact the section 678 // will have on the rest of the linker. That is why we copy the flags from 679 // the previous sections. Only a few flags are needed to keep the impact low. 680 uint64_t Flags = SHF_ALLOC; 681 682 for (BaseCommand *Cmd : SectionCommands) { 683 auto *Sec = dyn_cast<OutputSection>(Cmd); 684 if (!Sec) 685 continue; 686 if (Sec->Live) { 687 Flags = Sec->Flags & (SHF_ALLOC | SHF_WRITE | SHF_EXECINSTR); 688 continue; 689 } 690 691 if (isAllSectionDescription(*Sec)) 692 continue; 693 694 Sec->Live = true; 695 Sec->Flags = Flags; 696 } 697 } 698 699 void LinkerScript::adjustSectionsAfterSorting() { 700 // Try and find an appropriate memory region to assign offsets in. 701 for (BaseCommand *Base : SectionCommands) { 702 if (auto *Sec = dyn_cast<OutputSection>(Base)) { 703 if (!Sec->Live) 704 continue; 705 Sec->MemRegion = findMemoryRegion(Sec); 706 // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 707 if (Sec->AlignExpr) 708 Sec->Alignment = 709 std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue()); 710 } 711 } 712 713 // If output section command doesn't specify any segments, 714 // and we haven't previously assigned any section to segment, 715 // then we simply assign section to the very first load segment. 716 // Below is an example of such linker script: 717 // PHDRS { seg PT_LOAD; } 718 // SECTIONS { .aaa : { *(.aaa) } } 719 std::vector<StringRef> DefPhdrs; 720 auto FirstPtLoad = 721 std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(), 722 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); 723 if (FirstPtLoad != PhdrsCommands.end()) 724 DefPhdrs.push_back(FirstPtLoad->Name); 725 726 // Walk the commands and propagate the program headers to commands that don't 727 // explicitly specify them. 728 for (BaseCommand *Base : SectionCommands) { 729 auto *Sec = dyn_cast<OutputSection>(Base); 730 if (!Sec) 731 continue; 732 733 if (Sec->Phdrs.empty()) { 734 // To match the bfd linker script behaviour, only propagate program 735 // headers to sections that are allocated. 736 if (Sec->Flags & SHF_ALLOC) 737 Sec->Phdrs = DefPhdrs; 738 } else { 739 DefPhdrs = Sec->Phdrs; 740 } 741 } 742 } 743 744 static OutputSection *findFirstSection(PhdrEntry *Load) { 745 for (OutputSection *Sec : OutputSections) 746 if (Sec->PtLoad == Load) 747 return Sec; 748 return nullptr; 749 } 750 751 // Try to find an address for the file and program headers output sections, 752 // which were unconditionally added to the first PT_LOAD segment earlier. 753 // 754 // When using the default layout, we check if the headers fit below the first 755 // allocated section. When using a linker script, we also check if the headers 756 // are covered by the output section. This allows omitting the headers by not 757 // leaving enough space for them in the linker script; this pattern is common 758 // in embedded systems. 759 // 760 // If there isn't enough space for these sections, we'll remove them from the 761 // PT_LOAD segment, and we'll also remove the PT_PHDR segment. 762 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) { 763 uint64_t Min = std::numeric_limits<uint64_t>::max(); 764 for (OutputSection *Sec : OutputSections) 765 if (Sec->Flags & SHF_ALLOC) 766 Min = std::min<uint64_t>(Min, Sec->Addr); 767 768 auto It = llvm::find_if( 769 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); 770 if (It == Phdrs.end()) 771 return; 772 PhdrEntry *FirstPTLoad = *It; 773 774 uint64_t HeaderSize = getHeaderSize(); 775 // When linker script with SECTIONS is being used, don't output headers 776 // unless there's a space for them. 777 uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0; 778 if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) { 779 Min = alignDown(Min - HeaderSize, Config->MaxPageSize); 780 Out::ElfHeader->Addr = Min; 781 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; 782 return; 783 } 784 785 Out::ElfHeader->PtLoad = nullptr; 786 Out::ProgramHeaders->PtLoad = nullptr; 787 FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad); 788 789 llvm::erase_if(Phdrs, 790 [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); 791 } 792 793 LinkerScript::AddressState::AddressState() { 794 for (auto &MRI : Script->MemoryRegions) { 795 const MemoryRegion *MR = MRI.second; 796 MemRegionOffset[MR] = MR->Origin; 797 } 798 } 799 800 // Assign addresses as instructed by linker script SECTIONS sub-commands. 801 void LinkerScript::assignAddresses() { 802 // By default linker scripts use an initial value of 0 for '.', but prefer 803 // -image-base if set. 804 Dot = Config->ImageBase ? *Config->ImageBase : 0; 805 806 // Ctx captures the local AddressState and makes it accessible 807 // deliberately. This is needed as there are some cases where we cannot just 808 // thread the current state through to a lambda function created by the 809 // script parser. 810 Ctx = make_unique<AddressState>(); 811 ErrorOnMissingSection = true; 812 switchTo(Aether); 813 814 for (BaseCommand *Base : SectionCommands) { 815 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 816 assignSymbol(Cmd, false); 817 continue; 818 } 819 820 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) { 821 Cmd->Expression(); 822 continue; 823 } 824 825 assignOffsets(cast<OutputSection>(Base)); 826 } 827 Ctx = nullptr; 828 } 829 830 // Creates program headers as instructed by PHDRS linker script command. 831 std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 832 std::vector<PhdrEntry *> Ret; 833 834 // Process PHDRS and FILEHDR keywords because they are not 835 // real output sections and cannot be added in the following loop. 836 for (const PhdrsCommand &Cmd : PhdrsCommands) { 837 PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R); 838 839 if (Cmd.HasFilehdr) 840 Phdr->add(Out::ElfHeader); 841 if (Cmd.HasPhdrs) 842 Phdr->add(Out::ProgramHeaders); 843 844 if (Cmd.LMAExpr) { 845 Phdr->p_paddr = Cmd.LMAExpr().getValue(); 846 Phdr->HasLMA = true; 847 } 848 Ret.push_back(Phdr); 849 } 850 851 // Add output sections to program headers. 852 for (OutputSection *Sec : OutputSections) { 853 // Assign headers specified by linker script 854 for (size_t Id : getPhdrIndices(Sec)) { 855 Ret[Id]->add(Sec); 856 if (!PhdrsCommands[Id].Flags.hasValue()) 857 Ret[Id]->p_flags |= Sec->getPhdrFlags(); 858 } 859 } 860 return Ret; 861 } 862 863 // Returns true if we should emit an .interp section. 864 // 865 // We usually do. But if PHDRS commands are given, and 866 // no PT_INTERP is there, there's no place to emit an 867 // .interp, so we don't do that in that case. 868 bool LinkerScript::needsInterpSection() { 869 if (PhdrsCommands.empty()) 870 return true; 871 for (PhdrsCommand &Cmd : PhdrsCommands) 872 if (Cmd.Type == PT_INTERP) 873 return true; 874 return false; 875 } 876 877 ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) { 878 if (Name == ".") { 879 if (Ctx) 880 return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc}; 881 error(Loc + ": unable to get location counter value"); 882 return 0; 883 } 884 885 if (auto *Sym = dyn_cast_or_null<DefinedRegular>(Symtab->find(Name))) 886 return {Sym->Section, false, Sym->Value, Loc}; 887 888 error(Loc + ": symbol not found: " + Name); 889 return 0; 890 } 891 892 // Returns the index of the segment named Name. 893 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec, 894 StringRef Name) { 895 for (size_t I = 0; I < Vec.size(); ++I) 896 if (Vec[I].Name == Name) 897 return I; 898 return None; 899 } 900 901 // Returns indices of ELF headers containing specific section. Each index is a 902 // zero based number of ELF header listed within PHDRS {} script block. 903 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) { 904 std::vector<size_t> Ret; 905 906 for (StringRef S : Cmd->Phdrs) { 907 if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S)) 908 Ret.push_back(*Idx); 909 else if (S != "NONE") 910 error(Cmd->Location + ": section header '" + S + 911 "' is not listed in PHDRS"); 912 } 913 return Ret; 914 } 915