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