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 OutputSection *firstIsecOut = 694 firstIsec->flags & SHF_LINK_ORDER 695 ? firstIsec->getLinkOrderDep()->getOutputSection() 696 : nullptr; 697 if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection()) 698 continue; 699 } 700 701 sec->recordSection(isec); 702 return nullptr; 703 } 704 705 OutputSection *sec = createSection(isec, outsecName); 706 v.push_back(sec); 707 return sec; 708 } 709 710 // Add sections that didn't match any sections command. 711 void LinkerScript::addOrphanSections() { 712 StringMap<TinyPtrVector<OutputSection *>> map; 713 std::vector<OutputSection *> v; 714 715 std::function<void(InputSectionBase *)> add; 716 add = [&](InputSectionBase *s) { 717 if (s->isLive() && !s->parent) { 718 orphanSections.push_back(s); 719 720 StringRef name = getOutputSectionName(s); 721 if (config->unique) { 722 v.push_back(createSection(s, name)); 723 } else if (OutputSection *sec = findByName(sectionCommands, name)) { 724 sec->recordSection(s); 725 } else { 726 if (OutputSection *os = addInputSec(map, s, name)) 727 v.push_back(os); 728 assert(isa<MergeInputSection>(s) || 729 s->getOutputSection()->sectionIndex == UINT32_MAX); 730 } 731 } 732 733 if (config->relocatable) 734 for (InputSectionBase *depSec : s->dependentSections) 735 if (depSec->flags & SHF_LINK_ORDER) 736 add(depSec); 737 }; 738 739 // For futher --emit-reloc handling code we need target output section 740 // to be created before we create relocation output section, so we want 741 // to create target sections first. We do not want priority handling 742 // for synthetic sections because them are special. 743 for (InputSectionBase *isec : inputSections) { 744 // In -r links, SHF_LINK_ORDER sections are added while adding their parent 745 // sections because we need to know the parent's output section before we 746 // can select an output section for the SHF_LINK_ORDER section. 747 if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) 748 continue; 749 750 if (auto *sec = dyn_cast<InputSection>(isec)) 751 if (InputSectionBase *rel = sec->getRelocatedSection()) 752 if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent)) 753 add(relIS); 754 add(isec); 755 } 756 757 // If no SECTIONS command was given, we should insert sections commands 758 // before others, so that we can handle scripts which refers them, 759 // for example: "foo = ABSOLUTE(ADDR(.text)));". 760 // When SECTIONS command is present we just add all orphans to the end. 761 if (hasSectionsCommand) 762 sectionCommands.insert(sectionCommands.end(), v.begin(), v.end()); 763 else 764 sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end()); 765 } 766 767 void LinkerScript::diagnoseOrphanHandling() const { 768 for (const InputSectionBase *sec : orphanSections) { 769 // Input SHT_REL[A] retained by --emit-relocs are ignored by 770 // computeInputSections(). Don't warn/error. 771 if (isa<InputSection>(sec) && 772 cast<InputSection>(sec)->getRelocatedSection()) 773 continue; 774 775 StringRef name = getOutputSectionName(sec); 776 if (config->orphanHandling == OrphanHandlingPolicy::Error) 777 error(toString(sec) + " is being placed in '" + name + "'"); 778 else if (config->orphanHandling == OrphanHandlingPolicy::Warn) 779 warn(toString(sec) + " is being placed in '" + name + "'"); 780 } 781 } 782 783 uint64_t LinkerScript::advance(uint64_t size, unsigned alignment) { 784 bool isTbss = 785 (ctx->outSec->flags & SHF_TLS) && ctx->outSec->type == SHT_NOBITS; 786 uint64_t start = isTbss ? dot + ctx->threadBssOffset : dot; 787 start = alignTo(start, alignment); 788 uint64_t end = start + size; 789 790 if (isTbss) 791 ctx->threadBssOffset = end - dot; 792 else 793 dot = end; 794 return end; 795 } 796 797 void LinkerScript::output(InputSection *s) { 798 assert(ctx->outSec == s->getParent()); 799 uint64_t before = advance(0, 1); 800 uint64_t pos = advance(s->getSize(), s->alignment); 801 s->outSecOff = pos - s->getSize() - ctx->outSec->addr; 802 803 // Update output section size after adding each section. This is so that 804 // SIZEOF works correctly in the case below: 805 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 806 expandOutputSection(pos - before); 807 } 808 809 void LinkerScript::switchTo(OutputSection *sec) { 810 ctx->outSec = sec; 811 812 uint64_t pos = advance(0, 1); 813 if (sec->addrExpr && script->hasSectionsCommand) { 814 // The alignment is ignored. 815 ctx->outSec->addr = pos; 816 } else { 817 // ctx->outSec->alignment is the max of ALIGN and the maximum of input 818 // section alignments. 819 ctx->outSec->addr = advance(0, ctx->outSec->alignment); 820 expandMemoryRegions(ctx->outSec->addr - pos); 821 } 822 } 823 824 // This function searches for a memory region to place the given output 825 // section in. If found, a pointer to the appropriate memory region is 826 // returned. Otherwise, a nullptr is returned. 827 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *sec) { 828 // If a memory region name was specified in the output section command, 829 // then try to find that region first. 830 if (!sec->memoryRegionName.empty()) { 831 if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName)) 832 return m; 833 error("memory region '" + sec->memoryRegionName + "' not declared"); 834 return nullptr; 835 } 836 837 // If at least one memory region is defined, all sections must 838 // belong to some memory region. Otherwise, we don't need to do 839 // anything for memory regions. 840 if (memoryRegions.empty()) 841 return nullptr; 842 843 // See if a region can be found by matching section flags. 844 for (auto &pair : memoryRegions) { 845 MemoryRegion *m = pair.second; 846 if ((m->flags & sec->flags) && (m->negFlags & sec->flags) == 0) 847 return m; 848 } 849 850 // Otherwise, no suitable region was found. 851 if (sec->flags & SHF_ALLOC) 852 error("no memory region specified for section '" + sec->name + "'"); 853 return nullptr; 854 } 855 856 static OutputSection *findFirstSection(PhdrEntry *load) { 857 for (OutputSection *sec : outputSections) 858 if (sec->ptLoad == load) 859 return sec; 860 return nullptr; 861 } 862 863 // This function assigns offsets to input sections and an output section 864 // for a single sections command (e.g. ".text { *(.text); }"). 865 void LinkerScript::assignOffsets(OutputSection *sec) { 866 const bool sameMemRegion = ctx->memRegion == sec->memRegion; 867 const bool prevLMARegionIsDefault = ctx->lmaRegion == nullptr; 868 const uint64_t savedDot = dot; 869 ctx->memRegion = sec->memRegion; 870 ctx->lmaRegion = sec->lmaRegion; 871 872 if (sec->flags & SHF_ALLOC) { 873 if (ctx->memRegion) 874 dot = ctx->memRegion->curPos; 875 if (sec->addrExpr) 876 setDot(sec->addrExpr, sec->location, false); 877 878 // If the address of the section has been moved forward by an explicit 879 // expression so that it now starts past the current curPos of the enclosing 880 // region, we need to expand the current region to account for the space 881 // between the previous section, if any, and the start of this section. 882 if (ctx->memRegion && ctx->memRegion->curPos < dot) 883 expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos, 884 ctx->memRegion->name, sec->name); 885 } else { 886 // Non-SHF_ALLOC sections have zero addresses. 887 dot = 0; 888 } 889 890 switchTo(sec); 891 892 // ctx->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT() or 893 // AT>, recompute ctx->lmaOffset; otherwise, if both previous/current LMA 894 // region is the default, and the two sections are in the same memory region, 895 // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates 896 // heuristics described in 897 // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html 898 if (sec->lmaExpr) 899 ctx->lmaOffset = sec->lmaExpr().getValue() - dot; 900 else if (MemoryRegion *mr = sec->lmaRegion) 901 ctx->lmaOffset = alignTo(mr->curPos, sec->alignment) - dot; 902 else if (!sameMemRegion || !prevLMARegionIsDefault) 903 ctx->lmaOffset = 0; 904 905 // Propagate ctx->lmaOffset to the first "non-header" section. 906 if (PhdrEntry *l = ctx->outSec->ptLoad) 907 if (sec == findFirstSection(l)) 908 l->lmaOffset = ctx->lmaOffset; 909 910 // We can call this method multiple times during the creation of 911 // thunks and want to start over calculation each time. 912 sec->size = 0; 913 914 // We visited SectionsCommands from processSectionCommands to 915 // layout sections. Now, we visit SectionsCommands again to fix 916 // section offsets. 917 for (BaseCommand *base : sec->sectionCommands) { 918 // This handles the assignments to symbol or to the dot. 919 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) { 920 cmd->addr = dot; 921 assignSymbol(cmd, true); 922 cmd->size = dot - cmd->addr; 923 continue; 924 } 925 926 // Handle BYTE(), SHORT(), LONG(), or QUAD(). 927 if (auto *cmd = dyn_cast<ByteCommand>(base)) { 928 cmd->offset = dot - ctx->outSec->addr; 929 dot += cmd->size; 930 expandOutputSection(cmd->size); 931 continue; 932 } 933 934 // Handle a single input section description command. 935 // It calculates and assigns the offsets for each section and also 936 // updates the output section size. 937 for (InputSection *sec : cast<InputSectionDescription>(base)->sections) 938 output(sec); 939 } 940 941 // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections 942 // as they are not part of the process image. 943 if (!(sec->flags & SHF_ALLOC)) 944 dot = savedDot; 945 } 946 947 static bool isDiscardable(OutputSection &sec) { 948 if (sec.name == "/DISCARD/") 949 return true; 950 951 // We do not remove empty sections that are explicitly 952 // assigned to any segment. 953 if (!sec.phdrs.empty()) 954 return false; 955 956 // We do not want to remove OutputSections with expressions that reference 957 // symbols even if the OutputSection is empty. We want to ensure that the 958 // expressions can be evaluated and report an error if they cannot. 959 if (sec.expressionsUseSymbols) 960 return false; 961 962 // OutputSections may be referenced by name in ADDR and LOADADDR expressions, 963 // as an empty Section can has a valid VMA and LMA we keep the OutputSection 964 // to maintain the integrity of the other Expression. 965 if (sec.usedInExpression) 966 return false; 967 968 for (BaseCommand *base : sec.sectionCommands) { 969 if (auto cmd = dyn_cast<SymbolAssignment>(base)) 970 // Don't create empty output sections just for unreferenced PROVIDE 971 // symbols. 972 if (cmd->name != "." && !cmd->sym) 973 continue; 974 975 if (!isa<InputSectionDescription>(*base)) 976 return false; 977 } 978 return true; 979 } 980 981 void LinkerScript::adjustSectionsBeforeSorting() { 982 // If the output section contains only symbol assignments, create a 983 // corresponding output section. The issue is what to do with linker script 984 // like ".foo : { symbol = 42; }". One option would be to convert it to 985 // "symbol = 42;". That is, move the symbol out of the empty section 986 // description. That seems to be what bfd does for this simple case. The 987 // problem is that this is not completely general. bfd will give up and 988 // create a dummy section too if there is a ". = . + 1" inside the section 989 // for example. 990 // Given that we want to create the section, we have to worry what impact 991 // it will have on the link. For example, if we just create a section with 992 // 0 for flags, it would change which PT_LOADs are created. 993 // We could remember that particular section is dummy and ignore it in 994 // other parts of the linker, but unfortunately there are quite a few places 995 // that would need to change: 996 // * The program header creation. 997 // * The orphan section placement. 998 // * The address assignment. 999 // The other option is to pick flags that minimize the impact the section 1000 // will have on the rest of the linker. That is why we copy the flags from 1001 // the previous sections. Only a few flags are needed to keep the impact low. 1002 uint64_t flags = SHF_ALLOC; 1003 1004 for (BaseCommand *&cmd : sectionCommands) { 1005 auto *sec = dyn_cast<OutputSection>(cmd); 1006 if (!sec) 1007 continue; 1008 1009 // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 1010 if (sec->alignExpr) 1011 sec->alignment = 1012 std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue()); 1013 1014 // The input section might have been removed (if it was an empty synthetic 1015 // section), but we at least know the flags. 1016 if (sec->hasInputSections) 1017 flags = sec->flags; 1018 1019 // We do not want to keep any special flags for output section 1020 // in case it is empty. 1021 bool isEmpty = (getFirstInputSection(sec) == nullptr); 1022 if (isEmpty) 1023 sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | 1024 SHF_WRITE | SHF_EXECINSTR); 1025 1026 if (isEmpty && isDiscardable(*sec)) { 1027 sec->markDead(); 1028 cmd = nullptr; 1029 } 1030 } 1031 1032 // It is common practice to use very generic linker scripts. So for any 1033 // given run some of the output sections in the script will be empty. 1034 // We could create corresponding empty output sections, but that would 1035 // clutter the output. 1036 // We instead remove trivially empty sections. The bfd linker seems even 1037 // more aggressive at removing them. 1038 llvm::erase_if(sectionCommands, [&](BaseCommand *base) { return !base; }); 1039 } 1040 1041 void LinkerScript::adjustSectionsAfterSorting() { 1042 // Try and find an appropriate memory region to assign offsets in. 1043 for (BaseCommand *base : sectionCommands) { 1044 if (auto *sec = dyn_cast<OutputSection>(base)) { 1045 if (!sec->lmaRegionName.empty()) { 1046 if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName)) 1047 sec->lmaRegion = m; 1048 else 1049 error("memory region '" + sec->lmaRegionName + "' not declared"); 1050 } 1051 sec->memRegion = findMemoryRegion(sec); 1052 } 1053 } 1054 1055 // If output section command doesn't specify any segments, 1056 // and we haven't previously assigned any section to segment, 1057 // then we simply assign section to the very first load segment. 1058 // Below is an example of such linker script: 1059 // PHDRS { seg PT_LOAD; } 1060 // SECTIONS { .aaa : { *(.aaa) } } 1061 std::vector<StringRef> defPhdrs; 1062 auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) { 1063 return cmd.type == PT_LOAD; 1064 }); 1065 if (firstPtLoad != phdrsCommands.end()) 1066 defPhdrs.push_back(firstPtLoad->name); 1067 1068 // Walk the commands and propagate the program headers to commands that don't 1069 // explicitly specify them. 1070 for (BaseCommand *base : sectionCommands) { 1071 auto *sec = dyn_cast<OutputSection>(base); 1072 if (!sec) 1073 continue; 1074 1075 if (sec->phdrs.empty()) { 1076 // To match the bfd linker script behaviour, only propagate program 1077 // headers to sections that are allocated. 1078 if (sec->flags & SHF_ALLOC) 1079 sec->phdrs = defPhdrs; 1080 } else { 1081 defPhdrs = sec->phdrs; 1082 } 1083 } 1084 } 1085 1086 static uint64_t computeBase(uint64_t min, bool allocateHeaders) { 1087 // If there is no SECTIONS or if the linkerscript is explicit about program 1088 // headers, do our best to allocate them. 1089 if (!script->hasSectionsCommand || allocateHeaders) 1090 return 0; 1091 // Otherwise only allocate program headers if that would not add a page. 1092 return alignDown(min, config->maxPageSize); 1093 } 1094 1095 // When the SECTIONS command is used, try to find an address for the file and 1096 // program headers output sections, which can be added to the first PT_LOAD 1097 // segment when program headers are created. 1098 // 1099 // We check if the headers fit below the first allocated section. If there isn't 1100 // enough space for these sections, we'll remove them from the PT_LOAD segment, 1101 // and we'll also remove the PT_PHDR segment. 1102 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &phdrs) { 1103 uint64_t min = std::numeric_limits<uint64_t>::max(); 1104 for (OutputSection *sec : outputSections) 1105 if (sec->flags & SHF_ALLOC) 1106 min = std::min<uint64_t>(min, sec->addr); 1107 1108 auto it = llvm::find_if( 1109 phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; }); 1110 if (it == phdrs.end()) 1111 return; 1112 PhdrEntry *firstPTLoad = *it; 1113 1114 bool hasExplicitHeaders = 1115 llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) { 1116 return cmd.hasPhdrs || cmd.hasFilehdr; 1117 }); 1118 bool paged = !config->omagic && !config->nmagic; 1119 uint64_t headerSize = getHeaderSize(); 1120 if ((paged || hasExplicitHeaders) && 1121 headerSize <= min - computeBase(min, hasExplicitHeaders)) { 1122 min = alignDown(min - headerSize, config->maxPageSize); 1123 Out::elfHeader->addr = min; 1124 Out::programHeaders->addr = min + Out::elfHeader->size; 1125 return; 1126 } 1127 1128 // Error if we were explicitly asked to allocate headers. 1129 if (hasExplicitHeaders) 1130 error("could not allocate headers"); 1131 1132 Out::elfHeader->ptLoad = nullptr; 1133 Out::programHeaders->ptLoad = nullptr; 1134 firstPTLoad->firstSec = findFirstSection(firstPTLoad); 1135 1136 llvm::erase_if(phdrs, 1137 [](const PhdrEntry *e) { return e->p_type == PT_PHDR; }); 1138 } 1139 1140 LinkerScript::AddressState::AddressState() { 1141 for (auto &mri : script->memoryRegions) { 1142 MemoryRegion *mr = mri.second; 1143 mr->curPos = (mr->origin)().getValue(); 1144 } 1145 } 1146 1147 // Here we assign addresses as instructed by linker script SECTIONS 1148 // sub-commands. Doing that allows us to use final VA values, so here 1149 // we also handle rest commands like symbol assignments and ASSERTs. 1150 // Returns a symbol that has changed its section or value, or nullptr if no 1151 // symbol has changed. 1152 const Defined *LinkerScript::assignAddresses() { 1153 if (script->hasSectionsCommand) { 1154 // With a linker script, assignment of addresses to headers is covered by 1155 // allocateHeaders(). 1156 dot = config->imageBase.getValueOr(0); 1157 } else { 1158 // Assign addresses to headers right now. 1159 dot = target->getImageBase(); 1160 Out::elfHeader->addr = dot; 1161 Out::programHeaders->addr = dot + Out::elfHeader->size; 1162 dot += getHeaderSize(); 1163 } 1164 1165 auto deleter = std::make_unique<AddressState>(); 1166 ctx = deleter.get(); 1167 errorOnMissingSection = true; 1168 switchTo(aether); 1169 1170 SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands); 1171 for (BaseCommand *base : sectionCommands) { 1172 if (auto *cmd = dyn_cast<SymbolAssignment>(base)) { 1173 cmd->addr = dot; 1174 assignSymbol(cmd, false); 1175 cmd->size = dot - cmd->addr; 1176 continue; 1177 } 1178 assignOffsets(cast<OutputSection>(base)); 1179 } 1180 1181 ctx = nullptr; 1182 return getChangedSymbolAssignment(oldValues); 1183 } 1184 1185 // Creates program headers as instructed by PHDRS linker script command. 1186 std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 1187 std::vector<PhdrEntry *> ret; 1188 1189 // Process PHDRS and FILEHDR keywords because they are not 1190 // real output sections and cannot be added in the following loop. 1191 for (const PhdrsCommand &cmd : phdrsCommands) { 1192 PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags ? *cmd.flags : PF_R); 1193 1194 if (cmd.hasFilehdr) 1195 phdr->add(Out::elfHeader); 1196 if (cmd.hasPhdrs) 1197 phdr->add(Out::programHeaders); 1198 1199 if (cmd.lmaExpr) { 1200 phdr->p_paddr = cmd.lmaExpr().getValue(); 1201 phdr->hasLMA = true; 1202 } 1203 ret.push_back(phdr); 1204 } 1205 1206 // Add output sections to program headers. 1207 for (OutputSection *sec : outputSections) { 1208 // Assign headers specified by linker script 1209 for (size_t id : getPhdrIndices(sec)) { 1210 ret[id]->add(sec); 1211 if (!phdrsCommands[id].flags.hasValue()) 1212 ret[id]->p_flags |= sec->getPhdrFlags(); 1213 } 1214 } 1215 return ret; 1216 } 1217 1218 // Returns true if we should emit an .interp section. 1219 // 1220 // We usually do. But if PHDRS commands are given, and 1221 // no PT_INTERP is there, there's no place to emit an 1222 // .interp, so we don't do that in that case. 1223 bool LinkerScript::needsInterpSection() { 1224 if (phdrsCommands.empty()) 1225 return true; 1226 for (PhdrsCommand &cmd : phdrsCommands) 1227 if (cmd.type == PT_INTERP) 1228 return true; 1229 return false; 1230 } 1231 1232 ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) { 1233 if (name == ".") { 1234 if (ctx) 1235 return {ctx->outSec, false, dot - ctx->outSec->addr, loc}; 1236 error(loc + ": unable to get location counter value"); 1237 return 0; 1238 } 1239 1240 if (Symbol *sym = symtab->find(name)) { 1241 if (auto *ds = dyn_cast<Defined>(sym)) { 1242 ExprValue v{ds->section, false, ds->value, loc}; 1243 // Retain the original st_type, so that the alias will get the same 1244 // behavior in relocation processing. Any operation will reset st_type to 1245 // STT_NOTYPE. 1246 v.type = ds->type; 1247 return v; 1248 } 1249 if (isa<SharedSymbol>(sym)) 1250 if (!errorOnMissingSection) 1251 return {nullptr, false, 0, loc}; 1252 } 1253 1254 error(loc + ": symbol not found: " + name); 1255 return 0; 1256 } 1257 1258 // Returns the index of the segment named Name. 1259 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec, 1260 StringRef name) { 1261 for (size_t i = 0; i < vec.size(); ++i) 1262 if (vec[i].name == name) 1263 return i; 1264 return None; 1265 } 1266 1267 // Returns indices of ELF headers containing specific section. Each index is a 1268 // zero based number of ELF header listed within PHDRS {} script block. 1269 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *cmd) { 1270 std::vector<size_t> ret; 1271 1272 for (StringRef s : cmd->phdrs) { 1273 if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s)) 1274 ret.push_back(*idx); 1275 else if (s != "NONE") 1276 error(cmd->location + ": program header '" + s + 1277 "' is not listed in PHDRS"); 1278 } 1279 return ret; 1280 } 1281