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