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