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 47 namespace lld { 48 namespace elf { 49 LinkerScript *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 = std::string(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 std::string(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 (s->flags & id->withFlags) == id->withFlags && 340 (s->flags & id->withoutFlags) == 0) 341 return true; 342 return false; 343 } 344 345 // A helper function for the SORT() command. 346 static bool matchConstraints(ArrayRef<InputSectionBase *> sections, 347 ConstraintKind kind) { 348 if (kind == ConstraintKind::NoConstraint) 349 return true; 350 351 bool isRW = llvm::any_of( 352 sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; }); 353 354 return (isRW && kind == ConstraintKind::ReadWrite) || 355 (!isRW && kind == ConstraintKind::ReadOnly); 356 } 357 358 static void sortSections(MutableArrayRef<InputSectionBase *> vec, 359 SortSectionPolicy k) { 360 auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) { 361 // ">" is not a mistake. Sections with larger alignments are placed 362 // before sections with smaller alignments in order to reduce the 363 // amount of padding necessary. This is compatible with GNU. 364 return a->alignment > b->alignment; 365 }; 366 auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) { 367 return a->name < b->name; 368 }; 369 auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) { 370 return getPriority(a->name) < getPriority(b->name); 371 }; 372 373 switch (k) { 374 case SortSectionPolicy::Default: 375 case SortSectionPolicy::None: 376 return; 377 case SortSectionPolicy::Alignment: 378 return llvm::stable_sort(vec, alignmentComparator); 379 case SortSectionPolicy::Name: 380 return llvm::stable_sort(vec, nameComparator); 381 case SortSectionPolicy::Priority: 382 return llvm::stable_sort(vec, priorityComparator); 383 } 384 } 385 386 // Sort sections as instructed by SORT-family commands and --sort-section 387 // option. Because SORT-family commands can be nested at most two depth 388 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 389 // line option is respected even if a SORT command is given, the exact 390 // behavior we have here is a bit complicated. Here are the rules. 391 // 392 // 1. If two SORT commands are given, --sort-section is ignored. 393 // 2. If one SORT command is given, and if it is not SORT_NONE, 394 // --sort-section is handled as an inner SORT command. 395 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 396 // 4. If no SORT command is given, sort according to --sort-section. 397 static void sortInputSections(MutableArrayRef<InputSectionBase *> vec, 398 const SectionPattern &pat) { 399 if (pat.sortOuter == SortSectionPolicy::None) 400 return; 401 402 if (pat.sortInner == SortSectionPolicy::Default) 403 sortSections(vec, config->sortSection); 404 else 405 sortSections(vec, pat.sortInner); 406 sortSections(vec, pat.sortOuter); 407 } 408 409 // Compute and remember which sections the InputSectionDescription matches. 410 std::vector<InputSectionBase *> 411 LinkerScript::computeInputSections(const InputSectionDescription *cmd) { 412 std::vector<InputSectionBase *> ret; 413 414 // Collects all sections that satisfy constraints of Cmd. 415 for (const SectionPattern &pat : cmd->sectionPatterns) { 416 size_t sizeBefore = ret.size(); 417 418 for (InputSectionBase *sec : inputSections) { 419 if (!sec->isLive() || sec->parent) 420 continue; 421 422 // For -emit-relocs we have to ignore entries like 423 // .rela.dyn : { *(.rela.data) } 424 // which are common because they are in the default bfd script. 425 // We do not ignore SHT_REL[A] linker-synthesized sections here because 426 // want to support scripts that do custom layout for them. 427 if (isa<InputSection>(sec) && 428 cast<InputSection>(sec)->getRelocatedSection()) 429 continue; 430 431 // Check the name early to improve performance in the common case. 432 if (!pat.sectionPat.match(sec->name)) 433 continue; 434 435 std::string filename = getFilename(sec->file); 436 if (!cmd->filePat.match(filename) || 437 pat.excludedFilePat.match(filename) || 438 (sec->flags & cmd->withFlags) != cmd->withFlags || 439 (sec->flags & cmd->withoutFlags) != 0) 440 continue; 441 442 ret.push_back(sec); 443 } 444 445 sortInputSections( 446 MutableArrayRef<InputSectionBase *>(ret).slice(sizeBefore), pat); 447 } 448 return ret; 449 } 450 451 void LinkerScript::discard(InputSectionBase *s) { 452 if (s == in.shStrTab || s == mainPart->relrDyn) 453 error("discarding " + s->name + " section is not allowed"); 454 455 // You can discard .hash and .gnu.hash sections by linker scripts. Since 456 // they are synthesized sections, we need to handle them differently than 457 // other regular sections. 458 if (s == mainPart->gnuHashTab) 459 mainPart->gnuHashTab = nullptr; 460 if (s == mainPart->hashTab) 461 mainPart->hashTab = nullptr; 462 463 s->markDead(); 464 s->parent = nullptr; 465 for (InputSection *ds : s->dependentSections) 466 discard(ds); 467 } 468 469 std::vector<InputSectionBase *> 470 LinkerScript::createInputSectionList(OutputSection &outCmd) { 471 std::vector<InputSectionBase *> ret; 472 473 for (BaseCommand *base : outCmd.sectionCommands) { 474 if (auto *cmd = dyn_cast<InputSectionDescription>(base)) { 475 cmd->sectionBases = computeInputSections(cmd); 476 for (InputSectionBase *s : cmd->sectionBases) 477 s->parent = &outCmd; 478 ret.insert(ret.end(), cmd->sectionBases.begin(), cmd->sectionBases.end()); 479 } 480 } 481 return ret; 482 } 483 484 // Create output sections described by SECTIONS commands. 485 void LinkerScript::processSectionCommands() { 486 size_t i = 0; 487 for (BaseCommand *base : sectionCommands) { 488 if (auto *sec = dyn_cast<OutputSection>(base)) { 489 std::vector<InputSectionBase *> v = createInputSectionList(*sec); 490 491 // The output section name `/DISCARD/' is special. 492 // Any input section assigned to it is discarded. 493 if (sec->name == "/DISCARD/") { 494 for (InputSectionBase *s : v) 495 discard(s); 496 sec->sectionCommands.clear(); 497 continue; 498 } 499 500 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive 501 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input 502 // sections satisfy a given constraint. If not, a directive is handled 503 // as if it wasn't present from the beginning. 504 // 505 // Because we'll iterate over SectionCommands many more times, the easy 506 // way to "make it as if it wasn't present" is to make it empty. 507 if (!matchConstraints(v, sec->constraint)) { 508 for (InputSectionBase *s : v) 509 s->parent = nullptr; 510 sec->sectionCommands.clear(); 511 continue; 512 } 513 514 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign 515 // is given, input sections are aligned to that value, whether the 516 // given value is larger or smaller than the original section alignment. 517 if (sec->subalignExpr) { 518 uint32_t subalign = sec->subalignExpr().getValue(); 519 for (InputSectionBase *s : v) 520 s->alignment = subalign; 521 } 522 523 // Set the partition field the same way OutputSection::recordSection() 524 // does. Partitions cannot be used with the SECTIONS command, so this is 525 // always 1. 526 sec->partition = 1; 527 528 sec->sectionIndex = i++; 529 } 530 } 531 } 532 533 void LinkerScript::processSymbolAssignments() { 534 // Dot outside an output section still represents a relative address, whose 535 // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section 536 // that fills the void outside a section. It has an index of one, which is 537 // indistinguishable from any other regular section index. 538 aether = make<OutputSection>("", 0, SHF_ALLOC); 539 aether->sectionIndex = 1; 540 541 // ctx captures the local AddressState and makes it accessible deliberately. 542 // This is needed as there are some cases where we cannot just thread the 543 // current state through to a lambda function created by the script parser. 544 AddressState state; 545 ctx = &state; 546 ctx->outSec = aether; 547 548 for (BaseCommand *base : sectionCommands) { 549 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) 550 addSymbol(cmd); 551 else 552 for (BaseCommand *sub_base : cast<OutputSection>(base)->sectionCommands) 553 if (auto *cmd = dyn_cast<SymbolAssignment>(sub_base)) 554 addSymbol(cmd); 555 } 556 557 ctx = nullptr; 558 } 559 560 static OutputSection *findByName(ArrayRef<BaseCommand *> vec, 561 StringRef name) { 562 for (BaseCommand *base : vec) 563 if (auto *sec = dyn_cast<OutputSection>(base)) 564 if (sec->name == name) 565 return sec; 566 return nullptr; 567 } 568 569 static OutputSection *createSection(InputSectionBase *isec, 570 StringRef outsecName) { 571 OutputSection *sec = script->createOutputSection(outsecName, "<internal>"); 572 sec->recordSection(isec); 573 return sec; 574 } 575 576 static OutputSection * 577 addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map, 578 InputSectionBase *isec, StringRef outsecName) { 579 // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r 580 // option is given. A section with SHT_GROUP defines a "section group", and 581 // its members have SHF_GROUP attribute. Usually these flags have already been 582 // stripped by InputFiles.cpp as section groups are processed and uniquified. 583 // However, for the -r option, we want to pass through all section groups 584 // as-is because adding/removing members or merging them with other groups 585 // change their semantics. 586 if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP)) 587 return createSection(isec, outsecName); 588 589 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have 590 // relocation sections .rela.foo and .rela.bar for example. Most tools do 591 // not allow multiple REL[A] sections for output section. Hence we 592 // should combine these relocation sections into single output. 593 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any 594 // other REL[A] sections created by linker itself. 595 if (!isa<SyntheticSection>(isec) && 596 (isec->type == SHT_REL || isec->type == SHT_RELA)) { 597 auto *sec = cast<InputSection>(isec); 598 OutputSection *out = sec->getRelocatedSection()->getOutputSection(); 599 600 if (out->relocationSection) { 601 out->relocationSection->recordSection(sec); 602 return nullptr; 603 } 604 605 out->relocationSection = createSection(isec, outsecName); 606 return out->relocationSection; 607 } 608 609 // The ELF spec just says 610 // ---------------------------------------------------------------- 611 // In the first phase, input sections that match in name, type and 612 // attribute flags should be concatenated into single sections. 613 // ---------------------------------------------------------------- 614 // 615 // However, it is clear that at least some flags have to be ignored for 616 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be 617 // ignored. We should not have two output .text sections just because one was 618 // in a group and another was not for example. 619 // 620 // It also seems that wording was a late addition and didn't get the 621 // necessary scrutiny. 622 // 623 // Merging sections with different flags is expected by some users. One 624 // reason is that if one file has 625 // 626 // int *const bar __attribute__((section(".foo"))) = (int *)0; 627 // 628 // gcc with -fPIC will produce a read only .foo section. But if another 629 // file has 630 // 631 // int zed; 632 // int *const bar __attribute__((section(".foo"))) = (int *)&zed; 633 // 634 // gcc with -fPIC will produce a read write section. 635 // 636 // Last but not least, when using linker script the merge rules are forced by 637 // the script. Unfortunately, linker scripts are name based. This means that 638 // expressions like *(.foo*) can refer to multiple input sections with 639 // different flags. We cannot put them in different output sections or we 640 // would produce wrong results for 641 // 642 // start = .; *(.foo.*) end = .; *(.bar) 643 // 644 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to 645 // another. The problem is that there is no way to layout those output 646 // sections such that the .foo sections are the only thing between the start 647 // and end symbols. 648 // 649 // Given the above issues, we instead merge sections by name and error on 650 // incompatible types and flags. 651 TinyPtrVector<OutputSection *> &v = map[outsecName]; 652 for (OutputSection *sec : v) { 653 if (sec->partition != isec->partition) 654 continue; 655 656 if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) { 657 // Merging two SHF_LINK_ORDER sections with different sh_link fields will 658 // change their semantics, so we only merge them in -r links if they will 659 // end up being linked to the same output section. The casts are fine 660 // because everything in the map was created by the orphan placement code. 661 auto *firstIsec = cast<InputSectionBase>( 662 cast<InputSectionDescription>(sec->sectionCommands[0]) 663 ->sectionBases[0]); 664 if (firstIsec->getLinkOrderDep()->getOutputSection() != 665 isec->getLinkOrderDep()->getOutputSection()) 666 continue; 667 } 668 669 sec->recordSection(isec); 670 return nullptr; 671 } 672 673 OutputSection *sec = createSection(isec, outsecName); 674 v.push_back(sec); 675 return sec; 676 } 677 678 // Add sections that didn't match any sections command. 679 void LinkerScript::addOrphanSections() { 680 StringMap<TinyPtrVector<OutputSection *>> map; 681 std::vector<OutputSection *> v; 682 683 std::function<void(InputSectionBase *)> add; 684 add = [&](InputSectionBase *s) { 685 if (s->isLive() && !s->parent) { 686 StringRef name = getOutputSectionName(s); 687 688 if (config->orphanHandling == OrphanHandlingPolicy::Error) 689 error(toString(s) + " is being placed in '" + name + "'"); 690 else if (config->orphanHandling == OrphanHandlingPolicy::Warn) 691 warn(toString(s) + " is being placed in '" + name + "'"); 692 693 if (OutputSection *sec = findByName(sectionCommands, name)) { 694 sec->recordSection(s); 695 } else { 696 if (OutputSection *os = addInputSec(map, s, name)) 697 v.push_back(os); 698 assert(isa<MergeInputSection>(s) || 699 s->getOutputSection()->sectionIndex == UINT32_MAX); 700 } 701 } 702 703 if (config->relocatable) 704 for (InputSectionBase *depSec : s->dependentSections) 705 if (depSec->flags & SHF_LINK_ORDER) 706 add(depSec); 707 }; 708 709 // For futher --emit-reloc handling code we need target output section 710 // to be created before we create relocation output section, so we want 711 // to create target sections first. We do not want priority handling 712 // for synthetic sections because them are special. 713 for (InputSectionBase *isec : inputSections) { 714 // In -r links, SHF_LINK_ORDER sections are added while adding their parent 715 // sections because we need to know the parent's output section before we 716 // can select an output section for the SHF_LINK_ORDER section. 717 if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) 718 continue; 719 720 if (auto *sec = dyn_cast<InputSection>(isec)) 721 if (InputSectionBase *rel = sec->getRelocatedSection()) 722 if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent)) 723 add(relIS); 724 add(isec); 725 } 726 727 // If no SECTIONS command was given, we should insert sections commands 728 // before others, so that we can handle scripts which refers them, 729 // for example: "foo = ABSOLUTE(ADDR(.text)));". 730 // When SECTIONS command is present we just add all orphans to the end. 731 if (hasSectionsCommand) 732 sectionCommands.insert(sectionCommands.end(), v.begin(), v.end()); 733 else 734 sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end()); 735 } 736 737 uint64_t LinkerScript::advance(uint64_t size, unsigned alignment) { 738 bool isTbss = 739 (ctx->outSec->flags & SHF_TLS) && ctx->outSec->type == SHT_NOBITS; 740 uint64_t start = isTbss ? dot + ctx->threadBssOffset : dot; 741 start = alignTo(start, alignment); 742 uint64_t end = start + size; 743 744 if (isTbss) 745 ctx->threadBssOffset = end - dot; 746 else 747 dot = end; 748 return end; 749 } 750 751 void LinkerScript::output(InputSection *s) { 752 assert(ctx->outSec == s->getParent()); 753 uint64_t before = advance(0, 1); 754 uint64_t pos = advance(s->getSize(), s->alignment); 755 s->outSecOff = pos - s->getSize() - ctx->outSec->addr; 756 757 // Update output section size after adding each section. This is so that 758 // SIZEOF works correctly in the case below: 759 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 760 expandOutputSection(pos - before); 761 } 762 763 void LinkerScript::switchTo(OutputSection *sec) { 764 ctx->outSec = sec; 765 766 uint64_t before = advance(0, 1); 767 ctx->outSec->addr = advance(0, ctx->outSec->alignment); 768 expandMemoryRegions(ctx->outSec->addr - before); 769 } 770 771 // This function searches for a memory region to place the given output 772 // section in. If found, a pointer to the appropriate memory region is 773 // returned. Otherwise, a nullptr is returned. 774 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *sec) { 775 // If a memory region name was specified in the output section command, 776 // then try to find that region first. 777 if (!sec->memoryRegionName.empty()) { 778 if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName)) 779 return m; 780 error("memory region '" + sec->memoryRegionName + "' not declared"); 781 return nullptr; 782 } 783 784 // If at least one memory region is defined, all sections must 785 // belong to some memory region. Otherwise, we don't need to do 786 // anything for memory regions. 787 if (memoryRegions.empty()) 788 return nullptr; 789 790 // See if a region can be found by matching section flags. 791 for (auto &pair : memoryRegions) { 792 MemoryRegion *m = pair.second; 793 if ((m->flags & sec->flags) && (m->negFlags & sec->flags) == 0) 794 return m; 795 } 796 797 // Otherwise, no suitable region was found. 798 if (sec->flags & SHF_ALLOC) 799 error("no memory region specified for section '" + sec->name + "'"); 800 return nullptr; 801 } 802 803 static OutputSection *findFirstSection(PhdrEntry *load) { 804 for (OutputSection *sec : outputSections) 805 if (sec->ptLoad == load) 806 return sec; 807 return nullptr; 808 } 809 810 // This function assigns offsets to input sections and an output section 811 // for a single sections command (e.g. ".text { *(.text); }"). 812 void LinkerScript::assignOffsets(OutputSection *sec) { 813 if (!(sec->flags & SHF_ALLOC)) 814 dot = 0; 815 816 ctx->memRegion = sec->memRegion; 817 ctx->lmaRegion = sec->lmaRegion; 818 if (ctx->memRegion) 819 dot = ctx->memRegion->curPos; 820 821 if ((sec->flags & SHF_ALLOC) && sec->addrExpr) 822 setDot(sec->addrExpr, sec->location, false); 823 824 // If the address of the section has been moved forward by an explicit 825 // expression so that it now starts past the current curPos of the enclosing 826 // region, we need to expand the current region to account for the space 827 // between the previous section, if any, and the start of this section. 828 if (ctx->memRegion && ctx->memRegion->curPos < dot) 829 expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos, 830 ctx->memRegion->name, sec->name); 831 832 switchTo(sec); 833 834 if (sec->lmaExpr) 835 ctx->lmaOffset = sec->lmaExpr().getValue() - dot; 836 837 if (MemoryRegion *mr = sec->lmaRegion) 838 ctx->lmaOffset = mr->curPos - dot; 839 840 // If neither AT nor AT> is specified for an allocatable section, the linker 841 // will set the LMA such that the difference between VMA and LMA for the 842 // section is the same as the preceding output section in the same region 843 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 844 // This, however, should only be done by the first "non-header" section 845 // in the segment. 846 if (PhdrEntry *l = ctx->outSec->ptLoad) 847 if (sec == findFirstSection(l)) 848 l->lmaOffset = ctx->lmaOffset; 849 850 // We can call this method multiple times during the creation of 851 // thunks and want to start over calculation each time. 852 sec->size = 0; 853 854 // We visited SectionsCommands from processSectionCommands to 855 // layout sections. Now, we visit SectionsCommands again to fix 856 // section offsets. 857 for (BaseCommand *base : sec->sectionCommands) { 858 // This handles the assignments to symbol or to the dot. 859 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) { 860 cmd->addr = dot; 861 assignSymbol(cmd, true); 862 cmd->size = dot - cmd->addr; 863 continue; 864 } 865 866 // Handle BYTE(), SHORT(), LONG(), or QUAD(). 867 if (auto *cmd = dyn_cast<ByteCommand>(base)) { 868 cmd->offset = dot - ctx->outSec->addr; 869 dot += cmd->size; 870 expandOutputSection(cmd->size); 871 continue; 872 } 873 874 // Handle a single input section description command. 875 // It calculates and assigns the offsets for each section and also 876 // updates the output section size. 877 for (InputSection *sec : cast<InputSectionDescription>(base)->sections) 878 output(sec); 879 } 880 } 881 882 static bool isDiscardable(OutputSection &sec) { 883 if (sec.name == "/DISCARD/") 884 return true; 885 886 // We do not remove empty sections that are explicitly 887 // assigned to any segment. 888 if (!sec.phdrs.empty()) 889 return false; 890 891 // We do not want to remove OutputSections with expressions that reference 892 // symbols even if the OutputSection is empty. We want to ensure that the 893 // expressions can be evaluated and report an error if they cannot. 894 if (sec.expressionsUseSymbols) 895 return false; 896 897 // OutputSections may be referenced by name in ADDR and LOADADDR expressions, 898 // as an empty Section can has a valid VMA and LMA we keep the OutputSection 899 // to maintain the integrity of the other Expression. 900 if (sec.usedInExpression) 901 return false; 902 903 for (BaseCommand *base : sec.sectionCommands) { 904 if (auto cmd = dyn_cast<SymbolAssignment>(base)) 905 // Don't create empty output sections just for unreferenced PROVIDE 906 // symbols. 907 if (cmd->name != "." && !cmd->sym) 908 continue; 909 910 if (!isa<InputSectionDescription>(*base)) 911 return false; 912 } 913 return true; 914 } 915 916 void LinkerScript::adjustSectionsBeforeSorting() { 917 // If the output section contains only symbol assignments, create a 918 // corresponding output section. The issue is what to do with linker script 919 // like ".foo : { symbol = 42; }". One option would be to convert it to 920 // "symbol = 42;". That is, move the symbol out of the empty section 921 // description. That seems to be what bfd does for this simple case. The 922 // problem is that this is not completely general. bfd will give up and 923 // create a dummy section too if there is a ". = . + 1" inside the section 924 // for example. 925 // Given that we want to create the section, we have to worry what impact 926 // it will have on the link. For example, if we just create a section with 927 // 0 for flags, it would change which PT_LOADs are created. 928 // We could remember that particular section is dummy and ignore it in 929 // other parts of the linker, but unfortunately there are quite a few places 930 // that would need to change: 931 // * The program header creation. 932 // * The orphan section placement. 933 // * The address assignment. 934 // The other option is to pick flags that minimize the impact the section 935 // will have on the rest of the linker. That is why we copy the flags from 936 // the previous sections. Only a few flags are needed to keep the impact low. 937 uint64_t flags = SHF_ALLOC; 938 939 for (BaseCommand *&cmd : sectionCommands) { 940 auto *sec = dyn_cast<OutputSection>(cmd); 941 if (!sec) 942 continue; 943 944 // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 945 if (sec->alignExpr) 946 sec->alignment = 947 std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue()); 948 949 // The input section might have been removed (if it was an empty synthetic 950 // section), but we at least know the flags. 951 if (sec->hasInputSections) 952 flags = sec->flags; 953 954 // We do not want to keep any special flags for output section 955 // in case it is empty. 956 bool isEmpty = (getFirstInputSection(sec) == nullptr); 957 if (isEmpty) 958 sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | 959 SHF_WRITE | SHF_EXECINSTR); 960 961 if (isEmpty && isDiscardable(*sec)) { 962 sec->markDead(); 963 cmd = nullptr; 964 } 965 } 966 967 // It is common practice to use very generic linker scripts. So for any 968 // given run some of the output sections in the script will be empty. 969 // We could create corresponding empty output sections, but that would 970 // clutter the output. 971 // We instead remove trivially empty sections. The bfd linker seems even 972 // more aggressive at removing them. 973 llvm::erase_if(sectionCommands, [&](BaseCommand *base) { return !base; }); 974 } 975 976 void LinkerScript::adjustSectionsAfterSorting() { 977 // Try and find an appropriate memory region to assign offsets in. 978 for (BaseCommand *base : sectionCommands) { 979 if (auto *sec = dyn_cast<OutputSection>(base)) { 980 if (!sec->lmaRegionName.empty()) { 981 if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName)) 982 sec->lmaRegion = m; 983 else 984 error("memory region '" + sec->lmaRegionName + "' not declared"); 985 } 986 sec->memRegion = findMemoryRegion(sec); 987 } 988 } 989 990 // If output section command doesn't specify any segments, 991 // and we haven't previously assigned any section to segment, 992 // then we simply assign section to the very first load segment. 993 // Below is an example of such linker script: 994 // PHDRS { seg PT_LOAD; } 995 // SECTIONS { .aaa : { *(.aaa) } } 996 std::vector<StringRef> defPhdrs; 997 auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) { 998 return cmd.type == PT_LOAD; 999 }); 1000 if (firstPtLoad != phdrsCommands.end()) 1001 defPhdrs.push_back(firstPtLoad->name); 1002 1003 // Walk the commands and propagate the program headers to commands that don't 1004 // explicitly specify them. 1005 for (BaseCommand *base : sectionCommands) { 1006 auto *sec = dyn_cast<OutputSection>(base); 1007 if (!sec) 1008 continue; 1009 1010 if (sec->phdrs.empty()) { 1011 // To match the bfd linker script behaviour, only propagate program 1012 // headers to sections that are allocated. 1013 if (sec->flags & SHF_ALLOC) 1014 sec->phdrs = defPhdrs; 1015 } else { 1016 defPhdrs = sec->phdrs; 1017 } 1018 } 1019 } 1020 1021 static uint64_t computeBase(uint64_t min, bool allocateHeaders) { 1022 // If there is no SECTIONS or if the linkerscript is explicit about program 1023 // headers, do our best to allocate them. 1024 if (!script->hasSectionsCommand || allocateHeaders) 1025 return 0; 1026 // Otherwise only allocate program headers if that would not add a page. 1027 return alignDown(min, config->maxPageSize); 1028 } 1029 1030 // When the SECTIONS command is used, try to find an address for the file and 1031 // program headers output sections, which can be added to the first PT_LOAD 1032 // segment when program headers are created. 1033 // 1034 // We check if the headers fit below the first allocated section. If there isn't 1035 // enough space for these sections, we'll remove them from the PT_LOAD segment, 1036 // and we'll also remove the PT_PHDR segment. 1037 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &phdrs) { 1038 uint64_t min = std::numeric_limits<uint64_t>::max(); 1039 for (OutputSection *sec : outputSections) 1040 if (sec->flags & SHF_ALLOC) 1041 min = std::min<uint64_t>(min, sec->addr); 1042 1043 auto it = llvm::find_if( 1044 phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; }); 1045 if (it == phdrs.end()) 1046 return; 1047 PhdrEntry *firstPTLoad = *it; 1048 1049 bool hasExplicitHeaders = 1050 llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) { 1051 return cmd.hasPhdrs || cmd.hasFilehdr; 1052 }); 1053 bool paged = !config->omagic && !config->nmagic; 1054 uint64_t headerSize = getHeaderSize(); 1055 if ((paged || hasExplicitHeaders) && 1056 headerSize <= min - computeBase(min, hasExplicitHeaders)) { 1057 min = alignDown(min - headerSize, config->maxPageSize); 1058 Out::elfHeader->addr = min; 1059 Out::programHeaders->addr = min + Out::elfHeader->size; 1060 return; 1061 } 1062 1063 // Error if we were explicitly asked to allocate headers. 1064 if (hasExplicitHeaders) 1065 error("could not allocate headers"); 1066 1067 Out::elfHeader->ptLoad = nullptr; 1068 Out::programHeaders->ptLoad = nullptr; 1069 firstPTLoad->firstSec = findFirstSection(firstPTLoad); 1070 1071 llvm::erase_if(phdrs, 1072 [](const PhdrEntry *e) { return e->p_type == PT_PHDR; }); 1073 } 1074 1075 LinkerScript::AddressState::AddressState() { 1076 for (auto &mri : script->memoryRegions) { 1077 MemoryRegion *mr = mri.second; 1078 mr->curPos = mr->origin; 1079 } 1080 } 1081 1082 // Here we assign addresses as instructed by linker script SECTIONS 1083 // sub-commands. Doing that allows us to use final VA values, so here 1084 // we also handle rest commands like symbol assignments and ASSERTs. 1085 // Returns a symbol that has changed its section or value, or nullptr if no 1086 // symbol has changed. 1087 const Defined *LinkerScript::assignAddresses() { 1088 if (script->hasSectionsCommand) { 1089 // With a linker script, assignment of addresses to headers is covered by 1090 // allocateHeaders(). 1091 dot = config->imageBase.getValueOr(0); 1092 } else { 1093 // Assign addresses to headers right now. 1094 dot = target->getImageBase(); 1095 Out::elfHeader->addr = dot; 1096 Out::programHeaders->addr = dot + Out::elfHeader->size; 1097 dot += getHeaderSize(); 1098 } 1099 1100 auto deleter = std::make_unique<AddressState>(); 1101 ctx = deleter.get(); 1102 errorOnMissingSection = true; 1103 switchTo(aether); 1104 1105 SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands); 1106 for (BaseCommand *base : sectionCommands) { 1107 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) { 1108 cmd->addr = dot; 1109 assignSymbol(cmd, false); 1110 cmd->size = dot - cmd->addr; 1111 continue; 1112 } 1113 assignOffsets(cast<OutputSection>(base)); 1114 } 1115 1116 ctx = nullptr; 1117 return getChangedSymbolAssignment(oldValues); 1118 } 1119 1120 // Creates program headers as instructed by PHDRS linker script command. 1121 std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 1122 std::vector<PhdrEntry *> ret; 1123 1124 // Process PHDRS and FILEHDR keywords because they are not 1125 // real output sections and cannot be added in the following loop. 1126 for (const PhdrsCommand &cmd : phdrsCommands) { 1127 PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags ? *cmd.flags : PF_R); 1128 1129 if (cmd.hasFilehdr) 1130 phdr->add(Out::elfHeader); 1131 if (cmd.hasPhdrs) 1132 phdr->add(Out::programHeaders); 1133 1134 if (cmd.lmaExpr) { 1135 phdr->p_paddr = cmd.lmaExpr().getValue(); 1136 phdr->hasLMA = true; 1137 } 1138 ret.push_back(phdr); 1139 } 1140 1141 // Add output sections to program headers. 1142 for (OutputSection *sec : outputSections) { 1143 // Assign headers specified by linker script 1144 for (size_t id : getPhdrIndices(sec)) { 1145 ret[id]->add(sec); 1146 if (!phdrsCommands[id].flags.hasValue()) 1147 ret[id]->p_flags |= sec->getPhdrFlags(); 1148 } 1149 } 1150 return ret; 1151 } 1152 1153 // Returns true if we should emit an .interp section. 1154 // 1155 // We usually do. But if PHDRS commands are given, and 1156 // no PT_INTERP is there, there's no place to emit an 1157 // .interp, so we don't do that in that case. 1158 bool LinkerScript::needsInterpSection() { 1159 if (phdrsCommands.empty()) 1160 return true; 1161 for (PhdrsCommand &cmd : phdrsCommands) 1162 if (cmd.type == PT_INTERP) 1163 return true; 1164 return false; 1165 } 1166 1167 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) { 1168 if (name == ".") { 1169 if (ctx) 1170 return {ctx->outSec, false, dot - ctx->outSec->addr, loc}; 1171 error(loc + ": unable to get location counter value"); 1172 return 0; 1173 } 1174 1175 if (Symbol *sym = symtab->find(name)) { 1176 if (auto *ds = dyn_cast<Defined>(sym)) 1177 return {ds->section, false, ds->value, loc}; 1178 if (isa<SharedSymbol>(sym)) 1179 if (!errorOnMissingSection) 1180 return {nullptr, false, 0, loc}; 1181 } 1182 1183 error(loc + ": symbol not found: " + name); 1184 return 0; 1185 } 1186 1187 // Returns the index of the segment named Name. 1188 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec, 1189 StringRef name) { 1190 for (size_t i = 0; i < vec.size(); ++i) 1191 if (vec[i].name == name) 1192 return i; 1193 return None; 1194 } 1195 1196 // Returns indices of ELF headers containing specific section. Each index is a 1197 // zero based number of ELF header listed within PHDRS {} script block. 1198 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *cmd) { 1199 std::vector<size_t> ret; 1200 1201 for (StringRef s : cmd->phdrs) { 1202 if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s)) 1203 ret.push_back(*idx); 1204 else if (s != "NONE") 1205 error(cmd->location + ": section header '" + s + 1206 "' is not listed in PHDRS"); 1207 } 1208 return ret; 1209 } 1210 1211 } // namespace elf 1212 } // namespace lld 1213