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