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