1 //===- LinkerScript.cpp ---------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the parser/evaluator of the linker script. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "LinkerScript.h" 14 #include "Config.h" 15 #include "InputSection.h" 16 #include "OutputSections.h" 17 #include "SymbolTable.h" 18 #include "Symbols.h" 19 #include "SyntheticSections.h" 20 #include "Target.h" 21 #include "Writer.h" 22 #include "lld/Common/Memory.h" 23 #include "lld/Common/Strings.h" 24 #include "lld/Common/Threads.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/BinaryFormat/ELF.h" 28 #include "llvm/Support/Casting.h" 29 #include "llvm/Support/Endian.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/FileSystem.h" 32 #include "llvm/Support/Path.h" 33 #include <algorithm> 34 #include <cassert> 35 #include <cstddef> 36 #include <cstdint> 37 #include <iterator> 38 #include <limits> 39 #include <string> 40 #include <vector> 41 42 using namespace llvm; 43 using namespace llvm::ELF; 44 using namespace llvm::object; 45 using namespace llvm::support::endian; 46 using namespace lld; 47 using namespace lld::elf; 48 49 LinkerScript *elf::Script; 50 51 static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) { 52 if (OutputSection *OS = InputSec->getOutputSection()) 53 return OS->Addr; 54 error(Loc + ": unable to evaluate expression: input section " + 55 InputSec->Name + " has no output section assigned"); 56 return 0; 57 } 58 59 uint64_t ExprValue::getValue() const { 60 if (Sec) 61 return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc), 62 Alignment); 63 return alignTo(Val, Alignment); 64 } 65 66 uint64_t ExprValue::getSecAddr() const { 67 if (Sec) 68 return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc); 69 return 0; 70 } 71 72 uint64_t ExprValue::getSectionOffset() const { 73 // If the alignment is trivial, we don't have to compute the full 74 // value to know the offset. This allows this function to succeed in 75 // cases where the output section is not yet known. 76 if (Alignment == 1 && (!Sec || !Sec->getOutputSection())) 77 return Val; 78 return getValue() - getSecAddr(); 79 } 80 81 OutputSection *LinkerScript::createOutputSection(StringRef Name, 82 StringRef Location) { 83 OutputSection *&SecRef = NameToOutputSection[Name]; 84 OutputSection *Sec; 85 if (SecRef && SecRef->Location.empty()) { 86 // There was a forward reference. 87 Sec = SecRef; 88 } else { 89 Sec = make<OutputSection>(Name, SHT_PROGBITS, 0); 90 if (!SecRef) 91 SecRef = Sec; 92 } 93 Sec->Location = Location; 94 return Sec; 95 } 96 97 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) { 98 OutputSection *&CmdRef = NameToOutputSection[Name]; 99 if (!CmdRef) 100 CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0); 101 return CmdRef; 102 } 103 104 // Expands the memory region by the specified size. 105 static void expandMemoryRegion(MemoryRegion *MemRegion, uint64_t Size, 106 StringRef RegionName, StringRef SecName) { 107 MemRegion->CurPos += Size; 108 uint64_t NewSize = MemRegion->CurPos - MemRegion->Origin; 109 if (NewSize > MemRegion->Length) 110 error("section '" + SecName + "' will not fit in region '" + RegionName + 111 "': overflowed by " + Twine(NewSize - MemRegion->Length) + " bytes"); 112 } 113 114 void LinkerScript::expandMemoryRegions(uint64_t Size) { 115 if (Ctx->MemRegion) 116 expandMemoryRegion(Ctx->MemRegion, Size, Ctx->MemRegion->Name, 117 Ctx->OutSec->Name); 118 // Only expand the LMARegion if it is different from MemRegion. 119 if (Ctx->LMARegion && Ctx->MemRegion != Ctx->LMARegion) 120 expandMemoryRegion(Ctx->LMARegion, Size, Ctx->LMARegion->Name, 121 Ctx->OutSec->Name); 122 } 123 124 void LinkerScript::expandOutputSection(uint64_t Size) { 125 Ctx->OutSec->Size += Size; 126 expandMemoryRegions(Size); 127 } 128 129 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { 130 uint64_t Val = E().getValue(); 131 if (Val < Dot && InSec) 132 error(Loc + ": unable to move location counter backward for: " + 133 Ctx->OutSec->Name); 134 135 // Update to location counter means update to section size. 136 if (InSec) 137 expandOutputSection(Val - Dot); 138 else if (Val > Dot) 139 expandMemoryRegions(Val - Dot); 140 141 Dot = Val; 142 } 143 144 // Used for handling linker symbol assignments, for both finalizing 145 // their values and doing early declarations. Returns true if symbol 146 // should be defined from linker script. 147 static bool shouldDefineSym(SymbolAssignment *Cmd) { 148 if (Cmd->Name == ".") 149 return false; 150 151 if (!Cmd->Provide) 152 return true; 153 154 // If a symbol was in PROVIDE(), we need to define it only 155 // when it is a referenced undefined symbol. 156 Symbol *B = Symtab->find(Cmd->Name); 157 if (B && !B->isDefined()) 158 return true; 159 return false; 160 } 161 162 // This function is called from processSectionCommands, 163 // while we are fixing the output section layout. 164 void LinkerScript::addSymbol(SymbolAssignment *Cmd) { 165 if (!shouldDefineSym(Cmd)) 166 return; 167 168 // Define a symbol. 169 Symbol *Sym; 170 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 171 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, Visibility, 172 /*CanOmitFromDynSym*/ false, 173 /*File*/ nullptr); 174 ExprValue Value = Cmd->Expression(); 175 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; 176 177 // When this function is called, section addresses have not been 178 // fixed yet. So, we may or may not know the value of the RHS 179 // expression. 180 // 181 // For example, if an expression is `x = 42`, we know x is always 42. 182 // However, if an expression is `x = .`, there's no way to know its 183 // value at the moment. 184 // 185 // We want to set symbol values early if we can. This allows us to 186 // use symbols as variables in linker scripts. Doing so allows us to 187 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`. 188 uint64_t SymValue = Value.Sec ? 0 : Value.getValue(); 189 190 replaceSymbol<Defined>(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility, 191 STT_NOTYPE, SymValue, 0, Sec); 192 Cmd->Sym = cast<Defined>(Sym); 193 } 194 195 // This function is called from LinkerScript::declareSymbols. 196 // It creates a placeholder symbol if needed. 197 static void declareSymbol(SymbolAssignment *Cmd) { 198 if (!shouldDefineSym(Cmd)) 199 return; 200 201 // We can't calculate final value right now. 202 Symbol *Sym; 203 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 204 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, Visibility, 205 /*CanOmitFromDynSym*/ false, 206 /*File*/ nullptr); 207 replaceSymbol<Defined>(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility, 208 STT_NOTYPE, 0, 0, nullptr); 209 Cmd->Sym = cast<Defined>(Sym); 210 Cmd->Provide = false; 211 Sym->ScriptDefined = true; 212 } 213 214 // This method is used to handle INSERT AFTER statement. Here we rebuild 215 // the list of script commands to mix sections inserted into. 216 void LinkerScript::processInsertCommands() { 217 std::vector<BaseCommand *> V; 218 auto Insert = [&](std::vector<BaseCommand *> &From) { 219 V.insert(V.end(), From.begin(), From.end()); 220 From.clear(); 221 }; 222 223 for (BaseCommand *Base : SectionCommands) { 224 if (auto *OS = dyn_cast<OutputSection>(Base)) { 225 Insert(InsertBeforeCommands[OS->Name]); 226 V.push_back(Base); 227 Insert(InsertAfterCommands[OS->Name]); 228 continue; 229 } 230 V.push_back(Base); 231 } 232 233 for (auto &Cmds : {InsertBeforeCommands, InsertAfterCommands}) 234 for (const std::pair<StringRef, std::vector<BaseCommand *>> &P : Cmds) 235 if (!P.second.empty()) 236 error("unable to INSERT AFTER/BEFORE " + P.first + 237 ": section not defined"); 238 239 SectionCommands = std::move(V); 240 } 241 242 // Symbols defined in script should not be inlined by LTO. At the same time 243 // we don't know their final values until late stages of link. Here we scan 244 // over symbol assignment commands and create placeholder symbols if needed. 245 void LinkerScript::declareSymbols() { 246 assert(!Ctx); 247 for (BaseCommand *Base : SectionCommands) { 248 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 249 declareSymbol(Cmd); 250 continue; 251 } 252 253 // If the output section directive has constraints, 254 // we can't say for sure if it is going to be included or not. 255 // Skip such sections for now. Improve the checks if we ever 256 // need symbols from that sections to be declared early. 257 auto *Sec = cast<OutputSection>(Base); 258 if (Sec->Constraint != ConstraintKind::NoConstraint) 259 continue; 260 for (BaseCommand *Base2 : Sec->SectionCommands) 261 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base2)) 262 declareSymbol(Cmd); 263 } 264 } 265 266 // This function is called from assignAddresses, while we are 267 // fixing the output section addresses. This function is supposed 268 // to set the final value for a given symbol assignment. 269 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { 270 if (Cmd->Name == ".") { 271 setDot(Cmd->Expression, Cmd->Location, InSec); 272 return; 273 } 274 275 if (!Cmd->Sym) 276 return; 277 278 ExprValue V = Cmd->Expression(); 279 if (V.isAbsolute()) { 280 Cmd->Sym->Section = nullptr; 281 Cmd->Sym->Value = V.getValue(); 282 } else { 283 Cmd->Sym->Section = V.Sec; 284 Cmd->Sym->Value = V.getSectionOffset(); 285 } 286 } 287 288 static std::string getFilename(InputFile *File) { 289 if (!File) 290 return ""; 291 if (File->ArchiveName.empty()) 292 return File->getName(); 293 return (File->ArchiveName + "(" + File->getName() + ")").str(); 294 } 295 296 bool LinkerScript::shouldKeep(InputSectionBase *S) { 297 if (KeptSections.empty()) 298 return false; 299 std::string Filename = getFilename(S->File); 300 for (InputSectionDescription *ID : KeptSections) 301 if (ID->FilePat.match(Filename)) 302 for (SectionPattern &P : ID->SectionPatterns) 303 if (P.SectionPat.match(S->Name)) 304 return true; 305 return false; 306 } 307 308 // A helper function for the SORT() command. 309 static std::function<bool(InputSectionBase *, InputSectionBase *)> 310 getComparator(SortSectionPolicy K) { 311 switch (K) { 312 case SortSectionPolicy::Alignment: 313 return [](InputSectionBase *A, InputSectionBase *B) { 314 // ">" is not a mistake. Sections with larger alignments are placed 315 // before sections with smaller alignments in order to reduce the 316 // amount of padding necessary. This is compatible with GNU. 317 return A->Alignment > B->Alignment; 318 }; 319 case SortSectionPolicy::Name: 320 return [](InputSectionBase *A, InputSectionBase *B) { 321 return A->Name < B->Name; 322 }; 323 case SortSectionPolicy::Priority: 324 return [](InputSectionBase *A, InputSectionBase *B) { 325 return getPriority(A->Name) < getPriority(B->Name); 326 }; 327 default: 328 llvm_unreachable("unknown sort policy"); 329 } 330 } 331 332 // A helper function for the SORT() command. 333 static bool matchConstraints(ArrayRef<InputSection *> Sections, 334 ConstraintKind Kind) { 335 if (Kind == ConstraintKind::NoConstraint) 336 return true; 337 338 bool IsRW = llvm::any_of( 339 Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; }); 340 341 return (IsRW && Kind == ConstraintKind::ReadWrite) || 342 (!IsRW && Kind == ConstraintKind::ReadOnly); 343 } 344 345 static void sortSections(MutableArrayRef<InputSection *> Vec, 346 SortSectionPolicy K) { 347 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 348 llvm::stable_sort(Vec, getComparator(K)); 349 } 350 351 // Sort sections as instructed by SORT-family commands and --sort-section 352 // option. Because SORT-family commands can be nested at most two depth 353 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 354 // line option is respected even if a SORT command is given, the exact 355 // behavior we have here is a bit complicated. Here are the rules. 356 // 357 // 1. If two SORT commands are given, --sort-section is ignored. 358 // 2. If one SORT command is given, and if it is not SORT_NONE, 359 // --sort-section is handled as an inner SORT command. 360 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 361 // 4. If no SORT command is given, sort according to --sort-section. 362 static void sortInputSections(MutableArrayRef<InputSection *> Vec, 363 const SectionPattern &Pat) { 364 if (Pat.SortOuter == SortSectionPolicy::None) 365 return; 366 367 if (Pat.SortInner == SortSectionPolicy::Default) 368 sortSections(Vec, Config->SortSection); 369 else 370 sortSections(Vec, Pat.SortInner); 371 sortSections(Vec, Pat.SortOuter); 372 } 373 374 // Compute and remember which sections the InputSectionDescription matches. 375 std::vector<InputSection *> 376 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) { 377 std::vector<InputSection *> Ret; 378 379 // Collects all sections that satisfy constraints of Cmd. 380 for (const SectionPattern &Pat : Cmd->SectionPatterns) { 381 size_t SizeBefore = Ret.size(); 382 383 for (InputSectionBase *Sec : InputSections) { 384 if (!Sec->Live || Sec->Assigned) 385 continue; 386 387 // For -emit-relocs we have to ignore entries like 388 // .rela.dyn : { *(.rela.data) } 389 // which are common because they are in the default bfd script. 390 // We do not ignore SHT_REL[A] linker-synthesized sections here because 391 // want to support scripts that do custom layout for them. 392 if (auto *IS = dyn_cast<InputSection>(Sec)) 393 if (IS->getRelocatedSection()) 394 continue; 395 396 std::string Filename = getFilename(Sec->File); 397 if (!Cmd->FilePat.match(Filename) || 398 Pat.ExcludedFilePat.match(Filename) || 399 !Pat.SectionPat.match(Sec->Name)) 400 continue; 401 402 // It is safe to assume that Sec is an InputSection 403 // because mergeable or EH input sections have already been 404 // handled and eliminated. 405 Ret.push_back(cast<InputSection>(Sec)); 406 Sec->Assigned = true; 407 } 408 409 sortInputSections(MutableArrayRef<InputSection *>(Ret).slice(SizeBefore), 410 Pat); 411 } 412 return Ret; 413 } 414 415 void LinkerScript::discard(ArrayRef<InputSection *> V) { 416 for (InputSection *S : V) { 417 if (S == In.ShStrTab || S == In.RelaDyn || S == In.RelrDyn) 418 error("discarding " + S->Name + " section is not allowed"); 419 420 // You can discard .hash and .gnu.hash sections by linker scripts. Since 421 // they are synthesized sections, we need to handle them differently than 422 // other regular sections. 423 if (S == In.GnuHashTab) 424 In.GnuHashTab = nullptr; 425 if (S == In.HashTab) 426 In.HashTab = nullptr; 427 428 S->Assigned = false; 429 S->Live = false; 430 discard(S->DependentSections); 431 } 432 } 433 434 std::vector<InputSection *> 435 LinkerScript::createInputSectionList(OutputSection &OutCmd) { 436 std::vector<InputSection *> Ret; 437 438 for (BaseCommand *Base : OutCmd.SectionCommands) { 439 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) { 440 Cmd->Sections = computeInputSections(Cmd); 441 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); 442 } 443 } 444 return Ret; 445 } 446 447 void LinkerScript::processSectionCommands() { 448 // A symbol can be assigned before any section is mentioned in the linker 449 // script. In an DSO, the symbol values are addresses, so the only important 450 // section values are: 451 // * SHN_UNDEF 452 // * SHN_ABS 453 // * Any value meaning a regular section. 454 // To handle that, create a dummy aether section that fills the void before 455 // the linker scripts switches to another section. It has an index of one 456 // which will map to whatever the first actual section is. 457 Aether = make<OutputSection>("", 0, SHF_ALLOC); 458 Aether->SectionIndex = 1; 459 460 // Ctx captures the local AddressState and makes it accessible deliberately. 461 // This is needed as there are some cases where we cannot just 462 // thread the current state through to a lambda function created by the 463 // script parser. 464 auto Deleter = make_unique<AddressState>(); 465 Ctx = Deleter.get(); 466 Ctx->OutSec = Aether; 467 468 size_t I = 0; 469 // Add input sections to output sections. 470 for (BaseCommand *Base : SectionCommands) { 471 // Handle symbol assignments outside of any output section. 472 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 473 addSymbol(Cmd); 474 continue; 475 } 476 477 if (auto *Sec = dyn_cast<OutputSection>(Base)) { 478 std::vector<InputSection *> V = createInputSectionList(*Sec); 479 480 // The output section name `/DISCARD/' is special. 481 // Any input section assigned to it is discarded. 482 if (Sec->Name == "/DISCARD/") { 483 discard(V); 484 Sec->SectionCommands.clear(); 485 Sec->SectionIndex = 0; // Not an orphan. 486 continue; 487 } 488 489 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive 490 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input 491 // sections satisfy a given constraint. If not, a directive is handled 492 // as if it wasn't present from the beginning. 493 // 494 // Because we'll iterate over SectionCommands many more times, the easy 495 // way to "make it as if it wasn't present" is to make it empty. 496 if (!matchConstraints(V, Sec->Constraint)) { 497 for (InputSectionBase *S : V) 498 S->Assigned = false; 499 Sec->SectionCommands.clear(); 500 continue; 501 } 502 503 // A directive may contain symbol definitions like this: 504 // ".foo : { ...; bar = .; }". Handle them. 505 for (BaseCommand *Base : Sec->SectionCommands) 506 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base)) 507 addSymbol(OutCmd); 508 509 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign 510 // is given, input sections are aligned to that value, whether the 511 // given value is larger or smaller than the original section alignment. 512 if (Sec->SubalignExpr) { 513 uint32_t Subalign = Sec->SubalignExpr().getValue(); 514 for (InputSectionBase *S : V) 515 S->Alignment = Subalign; 516 } 517 518 // Add input sections to an output section. 519 for (InputSection *S : V) 520 Sec->addSection(S); 521 522 Sec->SectionIndex = I++; 523 if (Sec->Noload) 524 Sec->Type = SHT_NOBITS; 525 if (Sec->NonAlloc) 526 Sec->Flags &= ~(uint64_t)SHF_ALLOC; 527 } 528 } 529 Ctx = nullptr; 530 } 531 532 static OutputSection *findByName(ArrayRef<BaseCommand *> Vec, 533 StringRef Name) { 534 for (BaseCommand *Base : Vec) 535 if (auto *Sec = dyn_cast<OutputSection>(Base)) 536 if (Sec->Name == Name) 537 return Sec; 538 return nullptr; 539 } 540 541 static OutputSection *createSection(InputSectionBase *IS, 542 StringRef OutsecName) { 543 OutputSection *Sec = Script->createOutputSection(OutsecName, "<internal>"); 544 Sec->addSection(cast<InputSection>(IS)); 545 return Sec; 546 } 547 548 static OutputSection *addInputSec(StringMap<OutputSection *> &Map, 549 InputSectionBase *IS, StringRef OutsecName) { 550 // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r 551 // option is given. A section with SHT_GROUP defines a "section group", and 552 // its members have SHF_GROUP attribute. Usually these flags have already been 553 // stripped by InputFiles.cpp as section groups are processed and uniquified. 554 // However, for the -r option, we want to pass through all section groups 555 // as-is because adding/removing members or merging them with other groups 556 // change their semantics. 557 if (IS->Type == SHT_GROUP || (IS->Flags & SHF_GROUP)) 558 return createSection(IS, OutsecName); 559 560 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have 561 // relocation sections .rela.foo and .rela.bar for example. Most tools do 562 // not allow multiple REL[A] sections for output section. Hence we 563 // should combine these relocation sections into single output. 564 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any 565 // other REL[A] sections created by linker itself. 566 if (!isa<SyntheticSection>(IS) && 567 (IS->Type == SHT_REL || IS->Type == SHT_RELA)) { 568 auto *Sec = cast<InputSection>(IS); 569 OutputSection *Out = Sec->getRelocatedSection()->getOutputSection(); 570 571 if (Out->RelocationSection) { 572 Out->RelocationSection->addSection(Sec); 573 return nullptr; 574 } 575 576 Out->RelocationSection = createSection(IS, OutsecName); 577 return Out->RelocationSection; 578 } 579 580 // When control reaches here, mergeable sections have already been merged into 581 // synthetic sections. For relocatable case we want to create one output 582 // section per syntetic section so that they have a valid sh_entsize. 583 if (Config->Relocatable && (IS->Flags & SHF_MERGE)) 584 return createSection(IS, OutsecName); 585 586 // The ELF spec just says 587 // ---------------------------------------------------------------- 588 // In the first phase, input sections that match in name, type and 589 // attribute flags should be concatenated into single sections. 590 // ---------------------------------------------------------------- 591 // 592 // However, it is clear that at least some flags have to be ignored for 593 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be 594 // ignored. We should not have two output .text sections just because one was 595 // in a group and another was not for example. 596 // 597 // It also seems that wording was a late addition and didn't get the 598 // necessary scrutiny. 599 // 600 // Merging sections with different flags is expected by some users. One 601 // reason is that if one file has 602 // 603 // int *const bar __attribute__((section(".foo"))) = (int *)0; 604 // 605 // gcc with -fPIC will produce a read only .foo section. But if another 606 // file has 607 // 608 // int zed; 609 // int *const bar __attribute__((section(".foo"))) = (int *)&zed; 610 // 611 // gcc with -fPIC will produce a read write section. 612 // 613 // Last but not least, when using linker script the merge rules are forced by 614 // the script. Unfortunately, linker scripts are name based. This means that 615 // expressions like *(.foo*) can refer to multiple input sections with 616 // different flags. We cannot put them in different output sections or we 617 // would produce wrong results for 618 // 619 // start = .; *(.foo.*) end = .; *(.bar) 620 // 621 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to 622 // another. The problem is that there is no way to layout those output 623 // sections such that the .foo sections are the only thing between the start 624 // and end symbols. 625 // 626 // Given the above issues, we instead merge sections by name and error on 627 // incompatible types and flags. 628 OutputSection *&Sec = Map[OutsecName]; 629 if (Sec) { 630 Sec->addSection(cast<InputSection>(IS)); 631 return nullptr; 632 } 633 634 Sec = createSection(IS, OutsecName); 635 return Sec; 636 } 637 638 // Add sections that didn't match any sections command. 639 void LinkerScript::addOrphanSections() { 640 StringMap<OutputSection *> Map; 641 std::vector<OutputSection *> V; 642 643 auto Add = [&](InputSectionBase *S) { 644 if (!S->Live || S->Parent) 645 return; 646 647 StringRef Name = getOutputSectionName(S); 648 649 if (Config->OrphanHandling == OrphanHandlingPolicy::Error) 650 error(toString(S) + " is being placed in '" + Name + "'"); 651 else if (Config->OrphanHandling == OrphanHandlingPolicy::Warn) 652 warn(toString(S) + " is being placed in '" + Name + "'"); 653 654 if (OutputSection *Sec = findByName(SectionCommands, Name)) { 655 Sec->addSection(cast<InputSection>(S)); 656 return; 657 } 658 659 if (OutputSection *OS = addInputSec(Map, S, Name)) 660 V.push_back(OS); 661 assert(S->getOutputSection()->SectionIndex == UINT32_MAX); 662 }; 663 664 // For futher --emit-reloc handling code we need target output section 665 // to be created before we create relocation output section, so we want 666 // to create target sections first. We do not want priority handling 667 // for synthetic sections because them are special. 668 for (InputSectionBase *IS : InputSections) { 669 if (auto *Sec = dyn_cast<InputSection>(IS)) 670 if (InputSectionBase *Rel = Sec->getRelocatedSection()) 671 if (auto *RelIS = dyn_cast_or_null<InputSectionBase>(Rel->Parent)) 672 Add(RelIS); 673 Add(IS); 674 } 675 676 // If no SECTIONS command was given, we should insert sections commands 677 // before others, so that we can handle scripts which refers them, 678 // for example: "foo = ABSOLUTE(ADDR(.text)));". 679 // When SECTIONS command is present we just add all orphans to the end. 680 if (HasSectionsCommand) 681 SectionCommands.insert(SectionCommands.end(), V.begin(), V.end()); 682 else 683 SectionCommands.insert(SectionCommands.begin(), V.begin(), V.end()); 684 } 685 686 uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) { 687 bool IsTbss = 688 (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS; 689 uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot; 690 Start = alignTo(Start, Alignment); 691 uint64_t End = Start + Size; 692 693 if (IsTbss) 694 Ctx->ThreadBssOffset = End - Dot; 695 else 696 Dot = End; 697 return End; 698 } 699 700 void LinkerScript::output(InputSection *S) { 701 assert(Ctx->OutSec == S->getParent()); 702 uint64_t Before = advance(0, 1); 703 uint64_t Pos = advance(S->getSize(), S->Alignment); 704 S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr; 705 706 // Update output section size after adding each section. This is so that 707 // SIZEOF works correctly in the case below: 708 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 709 expandOutputSection(Pos - Before); 710 } 711 712 void LinkerScript::switchTo(OutputSection *Sec) { 713 Ctx->OutSec = Sec; 714 715 uint64_t Before = advance(0, 1); 716 Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment); 717 expandMemoryRegions(Ctx->OutSec->Addr - Before); 718 } 719 720 // This function searches for a memory region to place the given output 721 // section in. If found, a pointer to the appropriate memory region is 722 // returned. Otherwise, a nullptr is returned. 723 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) { 724 // If a memory region name was specified in the output section command, 725 // then try to find that region first. 726 if (!Sec->MemoryRegionName.empty()) { 727 if (MemoryRegion *M = MemoryRegions.lookup(Sec->MemoryRegionName)) 728 return M; 729 error("memory region '" + Sec->MemoryRegionName + "' not declared"); 730 return nullptr; 731 } 732 733 // If at least one memory region is defined, all sections must 734 // belong to some memory region. Otherwise, we don't need to do 735 // anything for memory regions. 736 if (MemoryRegions.empty()) 737 return nullptr; 738 739 // See if a region can be found by matching section flags. 740 for (auto &Pair : MemoryRegions) { 741 MemoryRegion *M = Pair.second; 742 if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0) 743 return M; 744 } 745 746 // Otherwise, no suitable region was found. 747 if (Sec->Flags & SHF_ALLOC) 748 error("no memory region specified for section '" + Sec->Name + "'"); 749 return nullptr; 750 } 751 752 static OutputSection *findFirstSection(PhdrEntry *Load) { 753 for (OutputSection *Sec : OutputSections) 754 if (Sec->PtLoad == Load) 755 return Sec; 756 return nullptr; 757 } 758 759 // This function assigns offsets to input sections and an output section 760 // for a single sections command (e.g. ".text { *(.text); }"). 761 void LinkerScript::assignOffsets(OutputSection *Sec) { 762 if (!(Sec->Flags & SHF_ALLOC)) 763 Dot = 0; 764 765 Ctx->MemRegion = Sec->MemRegion; 766 Ctx->LMARegion = Sec->LMARegion; 767 if (Ctx->MemRegion) 768 Dot = Ctx->MemRegion->CurPos; 769 770 if ((Sec->Flags & SHF_ALLOC) && Sec->AddrExpr) 771 setDot(Sec->AddrExpr, Sec->Location, false); 772 773 switchTo(Sec); 774 775 if (Sec->LMAExpr) 776 Ctx->LMAOffset = Sec->LMAExpr().getValue() - Dot; 777 778 if (MemoryRegion *MR = Sec->LMARegion) 779 Ctx->LMAOffset = MR->CurPos - Dot; 780 781 // If neither AT nor AT> is specified for an allocatable section, the linker 782 // will set the LMA such that the difference between VMA and LMA for the 783 // section is the same as the preceding output section in the same region 784 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 785 // This, however, should only be done by the first "non-header" section 786 // in the segment. 787 if (PhdrEntry *L = Ctx->OutSec->PtLoad) 788 if (Sec == findFirstSection(L)) 789 L->LMAOffset = Ctx->LMAOffset; 790 791 // We can call this method multiple times during the creation of 792 // thunks and want to start over calculation each time. 793 Sec->Size = 0; 794 795 // We visited SectionsCommands from processSectionCommands to 796 // layout sections. Now, we visit SectionsCommands again to fix 797 // section offsets. 798 for (BaseCommand *Base : Sec->SectionCommands) { 799 // This handles the assignments to symbol or to the dot. 800 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 801 Cmd->Addr = Dot; 802 assignSymbol(Cmd, true); 803 Cmd->Size = Dot - Cmd->Addr; 804 continue; 805 } 806 807 // Handle BYTE(), SHORT(), LONG(), or QUAD(). 808 if (auto *Cmd = dyn_cast<ByteCommand>(Base)) { 809 Cmd->Offset = Dot - Ctx->OutSec->Addr; 810 Dot += Cmd->Size; 811 expandOutputSection(Cmd->Size); 812 continue; 813 } 814 815 // Handle a single input section description command. 816 // It calculates and assigns the offsets for each section and also 817 // updates the output section size. 818 for (InputSection *Sec : cast<InputSectionDescription>(Base)->Sections) 819 output(Sec); 820 } 821 } 822 823 static bool isDiscardable(OutputSection &Sec) { 824 // We do not remove empty sections that are explicitly 825 // assigned to any segment. 826 if (!Sec.Phdrs.empty()) 827 return false; 828 829 // We do not want to remove OutputSections with expressions that reference 830 // symbols even if the OutputSection is empty. We want to ensure that the 831 // expressions can be evaluated and report an error if they cannot. 832 if (Sec.ExpressionsUseSymbols) 833 return false; 834 835 // OutputSections may be referenced by name in ADDR and LOADADDR expressions, 836 // as an empty Section can has a valid VMA and LMA we keep the OutputSection 837 // to maintain the integrity of the other Expression. 838 if (Sec.UsedInExpression) 839 return false; 840 841 for (BaseCommand *Base : Sec.SectionCommands) { 842 if (auto Cmd = dyn_cast<SymbolAssignment>(Base)) 843 // Don't create empty output sections just for unreferenced PROVIDE 844 // symbols. 845 if (Cmd->Name != "." && !Cmd->Sym) 846 continue; 847 848 if (!isa<InputSectionDescription>(*Base)) 849 return false; 850 } 851 return true; 852 } 853 854 void LinkerScript::adjustSectionsBeforeSorting() { 855 // If the output section contains only symbol assignments, create a 856 // corresponding output section. The issue is what to do with linker script 857 // like ".foo : { symbol = 42; }". One option would be to convert it to 858 // "symbol = 42;". That is, move the symbol out of the empty section 859 // description. That seems to be what bfd does for this simple case. The 860 // problem is that this is not completely general. bfd will give up and 861 // create a dummy section too if there is a ". = . + 1" inside the section 862 // for example. 863 // Given that we want to create the section, we have to worry what impact 864 // it will have on the link. For example, if we just create a section with 865 // 0 for flags, it would change which PT_LOADs are created. 866 // We could remember that particular section is dummy and ignore it in 867 // other parts of the linker, but unfortunately there are quite a few places 868 // that would need to change: 869 // * The program header creation. 870 // * The orphan section placement. 871 // * The address assignment. 872 // The other option is to pick flags that minimize the impact the section 873 // will have on the rest of the linker. That is why we copy the flags from 874 // the previous sections. Only a few flags are needed to keep the impact low. 875 uint64_t Flags = SHF_ALLOC; 876 877 for (BaseCommand *&Cmd : SectionCommands) { 878 auto *Sec = dyn_cast<OutputSection>(Cmd); 879 if (!Sec) 880 continue; 881 882 // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 883 if (Sec->AlignExpr) 884 Sec->Alignment = 885 std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue()); 886 887 // A live output section means that some input section was added to it. It 888 // might have been removed (if it was empty synthetic section), but we at 889 // least know the flags. 890 if (Sec->Live) 891 Flags = Sec->Flags; 892 893 // We do not want to keep any special flags for output section 894 // in case it is empty. 895 bool IsEmpty = getInputSections(Sec).empty(); 896 if (IsEmpty) 897 Sec->Flags = Flags & ((Sec->NonAlloc ? 0 : (uint64_t)SHF_ALLOC) | 898 SHF_WRITE | SHF_EXECINSTR); 899 900 if (IsEmpty && isDiscardable(*Sec)) { 901 Sec->Live = false; 902 Cmd = nullptr; 903 } 904 } 905 906 // It is common practice to use very generic linker scripts. So for any 907 // given run some of the output sections in the script will be empty. 908 // We could create corresponding empty output sections, but that would 909 // clutter the output. 910 // We instead remove trivially empty sections. The bfd linker seems even 911 // more aggressive at removing them. 912 llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { return !Base; }); 913 } 914 915 void LinkerScript::adjustSectionsAfterSorting() { 916 // Try and find an appropriate memory region to assign offsets in. 917 for (BaseCommand *Base : SectionCommands) { 918 if (auto *Sec = dyn_cast<OutputSection>(Base)) { 919 if (!Sec->LMARegionName.empty()) { 920 if (MemoryRegion *M = MemoryRegions.lookup(Sec->LMARegionName)) 921 Sec->LMARegion = M; 922 else 923 error("memory region '" + Sec->LMARegionName + "' not declared"); 924 } 925 Sec->MemRegion = findMemoryRegion(Sec); 926 } 927 } 928 929 // If output section command doesn't specify any segments, 930 // and we haven't previously assigned any section to segment, 931 // then we simply assign section to the very first load segment. 932 // Below is an example of such linker script: 933 // PHDRS { seg PT_LOAD; } 934 // SECTIONS { .aaa : { *(.aaa) } } 935 std::vector<StringRef> DefPhdrs; 936 auto FirstPtLoad = llvm::find_if(PhdrsCommands, [](const PhdrsCommand &Cmd) { 937 return Cmd.Type == PT_LOAD; 938 }); 939 if (FirstPtLoad != PhdrsCommands.end()) 940 DefPhdrs.push_back(FirstPtLoad->Name); 941 942 // Walk the commands and propagate the program headers to commands that don't 943 // explicitly specify them. 944 for (BaseCommand *Base : SectionCommands) { 945 auto *Sec = dyn_cast<OutputSection>(Base); 946 if (!Sec) 947 continue; 948 949 if (Sec->Phdrs.empty()) { 950 // To match the bfd linker script behaviour, only propagate program 951 // headers to sections that are allocated. 952 if (Sec->Flags & SHF_ALLOC) 953 Sec->Phdrs = DefPhdrs; 954 } else { 955 DefPhdrs = Sec->Phdrs; 956 } 957 } 958 } 959 960 static uint64_t computeBase(uint64_t Min, bool AllocateHeaders) { 961 // If there is no SECTIONS or if the linkerscript is explicit about program 962 // headers, do our best to allocate them. 963 if (!Script->HasSectionsCommand || AllocateHeaders) 964 return 0; 965 // Otherwise only allocate program headers if that would not add a page. 966 return alignDown(Min, Config->MaxPageSize); 967 } 968 969 // Try to find an address for the file and program headers output sections, 970 // which were unconditionally added to the first PT_LOAD segment earlier. 971 // 972 // When using the default layout, we check if the headers fit below the first 973 // allocated section. When using a linker script, we also check if the headers 974 // are covered by the output section. This allows omitting the headers by not 975 // leaving enough space for them in the linker script; this pattern is common 976 // in embedded systems. 977 // 978 // If there isn't enough space for these sections, we'll remove them from the 979 // PT_LOAD segment, and we'll also remove the PT_PHDR segment. 980 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) { 981 uint64_t Min = std::numeric_limits<uint64_t>::max(); 982 for (OutputSection *Sec : OutputSections) 983 if (Sec->Flags & SHF_ALLOC) 984 Min = std::min<uint64_t>(Min, Sec->Addr); 985 986 auto It = llvm::find_if( 987 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); 988 if (It == Phdrs.end()) 989 return; 990 PhdrEntry *FirstPTLoad = *It; 991 992 bool HasExplicitHeaders = 993 llvm::any_of(PhdrsCommands, [](const PhdrsCommand &Cmd) { 994 return Cmd.HasPhdrs || Cmd.HasFilehdr; 995 }); 996 bool Paged = !Config->Omagic && !Config->Nmagic; 997 uint64_t HeaderSize = getHeaderSize(); 998 if ((Paged || HasExplicitHeaders) && 999 HeaderSize <= Min - computeBase(Min, HasExplicitHeaders)) { 1000 Min = alignDown(Min - HeaderSize, Config->MaxPageSize); 1001 Out::ElfHeader->Addr = Min; 1002 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; 1003 return; 1004 } 1005 1006 // Error if we were explicitly asked to allocate headers. 1007 if (HasExplicitHeaders) 1008 error("could not allocate headers"); 1009 1010 Out::ElfHeader->PtLoad = nullptr; 1011 Out::ProgramHeaders->PtLoad = nullptr; 1012 FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad); 1013 1014 llvm::erase_if(Phdrs, 1015 [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); 1016 } 1017 1018 LinkerScript::AddressState::AddressState() { 1019 for (auto &MRI : Script->MemoryRegions) { 1020 MemoryRegion *MR = MRI.second; 1021 MR->CurPos = MR->Origin; 1022 } 1023 } 1024 1025 static uint64_t getInitialDot() { 1026 // By default linker scripts use an initial value of 0 for '.', 1027 // but prefer -image-base if set. 1028 if (Script->HasSectionsCommand) 1029 return Config->ImageBase ? *Config->ImageBase : 0; 1030 1031 uint64_t StartAddr = UINT64_MAX; 1032 // The Sections with -T<section> have been sorted in order of ascending 1033 // address. We must lower StartAddr if the lowest -T<section address> as 1034 // calls to setDot() must be monotonically increasing. 1035 for (auto &KV : Config->SectionStartMap) 1036 StartAddr = std::min(StartAddr, KV.second); 1037 return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize()); 1038 } 1039 1040 // Here we assign addresses as instructed by linker script SECTIONS 1041 // sub-commands. Doing that allows us to use final VA values, so here 1042 // we also handle rest commands like symbol assignments and ASSERTs. 1043 void LinkerScript::assignAddresses() { 1044 Dot = getInitialDot(); 1045 1046 auto Deleter = make_unique<AddressState>(); 1047 Ctx = Deleter.get(); 1048 ErrorOnMissingSection = true; 1049 switchTo(Aether); 1050 1051 for (BaseCommand *Base : SectionCommands) { 1052 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 1053 Cmd->Addr = Dot; 1054 assignSymbol(Cmd, false); 1055 Cmd->Size = Dot - Cmd->Addr; 1056 continue; 1057 } 1058 assignOffsets(cast<OutputSection>(Base)); 1059 } 1060 Ctx = nullptr; 1061 } 1062 1063 // Creates program headers as instructed by PHDRS linker script command. 1064 std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 1065 std::vector<PhdrEntry *> Ret; 1066 1067 // Process PHDRS and FILEHDR keywords because they are not 1068 // real output sections and cannot be added in the following loop. 1069 for (const PhdrsCommand &Cmd : PhdrsCommands) { 1070 PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R); 1071 1072 if (Cmd.HasFilehdr) 1073 Phdr->add(Out::ElfHeader); 1074 if (Cmd.HasPhdrs) 1075 Phdr->add(Out::ProgramHeaders); 1076 1077 if (Cmd.LMAExpr) { 1078 Phdr->p_paddr = Cmd.LMAExpr().getValue(); 1079 Phdr->HasLMA = true; 1080 } 1081 Ret.push_back(Phdr); 1082 } 1083 1084 // Add output sections to program headers. 1085 for (OutputSection *Sec : OutputSections) { 1086 // Assign headers specified by linker script 1087 for (size_t Id : getPhdrIndices(Sec)) { 1088 Ret[Id]->add(Sec); 1089 if (!PhdrsCommands[Id].Flags.hasValue()) 1090 Ret[Id]->p_flags |= Sec->getPhdrFlags(); 1091 } 1092 } 1093 return Ret; 1094 } 1095 1096 // Returns true if we should emit an .interp section. 1097 // 1098 // We usually do. But if PHDRS commands are given, and 1099 // no PT_INTERP is there, there's no place to emit an 1100 // .interp, so we don't do that in that case. 1101 bool LinkerScript::needsInterpSection() { 1102 if (PhdrsCommands.empty()) 1103 return true; 1104 for (PhdrsCommand &Cmd : PhdrsCommands) 1105 if (Cmd.Type == PT_INTERP) 1106 return true; 1107 return false; 1108 } 1109 1110 ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) { 1111 if (Name == ".") { 1112 if (Ctx) 1113 return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc}; 1114 error(Loc + ": unable to get location counter value"); 1115 return 0; 1116 } 1117 1118 if (Symbol *Sym = Symtab->find(Name)) { 1119 if (auto *DS = dyn_cast<Defined>(Sym)) 1120 return {DS->Section, false, DS->Value, Loc}; 1121 if (isa<SharedSymbol>(Sym)) 1122 if (!ErrorOnMissingSection) 1123 return {nullptr, false, 0, Loc}; 1124 } 1125 1126 error(Loc + ": symbol not found: " + Name); 1127 return 0; 1128 } 1129 1130 // Returns the index of the segment named Name. 1131 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec, 1132 StringRef Name) { 1133 for (size_t I = 0; I < Vec.size(); ++I) 1134 if (Vec[I].Name == Name) 1135 return I; 1136 return None; 1137 } 1138 1139 // Returns indices of ELF headers containing specific section. Each index is a 1140 // zero based number of ELF header listed within PHDRS {} script block. 1141 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) { 1142 std::vector<size_t> Ret; 1143 1144 for (StringRef S : Cmd->Phdrs) { 1145 if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S)) 1146 Ret.push_back(*Idx); 1147 else if (S != "NONE") 1148 error(Cmd->Location + ": section header '" + S + 1149 "' is not listed in PHDRS"); 1150 } 1151 return Ret; 1152 } 1153