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