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