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