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