Lines Matching +full:- +full:- +full:require +full:- +full:hashes

1 //===- Writer.cpp ---------------------------------------------------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
104 if (p->p_type != PT_LOAD)
106 if (!p->firstSec)
108 uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
116 removed.insert(it2->get());
118 if (removed.count(sec->ptLoad))
119 sec->ptLoad = nullptr;
128 if (!(s->flags & SHF_ALLOC) || !s->isLive() || s->type != SHT_NOTE)
131 copy->partition = part;
135 assert(ctx.ehInputSections[i]->isLive());
137 copy->partition = part;
148 Symbol *s = ctx.symtab->find(name);
149 if (!s || s->isDefined() || s->isCommon())
153 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
156 s->isUsedInRegularObj = true;
166 ctx.symtab->addSymbol(Defined{ctx, ctx.internalFile, name, STB_GLOBAL,
168 sym->isUsedInRegularObj = true;
175 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
180 if (ctx.symtab->find("_gp_disp"))
184 // pointer. This symbol is used in the code generated by .cpload pseudo-op
185 // in case of using -mno-shared option.
186 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
187 if (ctx.symtab->find("__gnu_local_gp"))
197 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
200 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
208 if (Symbol *s = ctx.symtab->find(gotSymName)) {
209 if (s->isDefined()) {
210 ErrAlways(ctx) << s->file << " cannot redefine linker defined symbol '"
219 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
244 if (ctx.script->hasSectionsCommand)
253 ctx.sym.end1 = add("end", -1);
254 ctx.sym.end2 = add("_end", -1);
255 ctx.sym.etext1 = add("etext", -1);
256 ctx.sym.etext2 = add("_etext", -1);
257 ctx.sym.edata1 = add("edata", -1);
258 ctx.sym.edata2 = add("_edata", -1);
263 for (auto [i, sec] : llvm::enumerate(sym.file->getSections()))
279 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
287 for (Symbol *sym : ctx.symtab->getSymbols()) {
289 if (d->section && !d->section->isLive())
290 demoteDefined(*d, sectionIndexMap[d->file]);
293 if (sym->isLazy() || (s && !cast<SharedFile>(s->file)->isNeeded)) {
294 uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
295 Undefined(ctx.internalFile, sym->getName(), binding, sym->stOther,
296 sym->type)
298 sym->versionId = VER_NDX_GLOBAL;
299 if (hasDynsym && sym->includeInDynsym(ctx))
300 sym->isExported = true;
305 sym->isPreemptible = sym->isExported && computeIsPreemptible(ctx, *sym);
311 for (SectionCommand *cmd : ctx.script->sectionCommands)
313 if (osd->osec.name == name && osd->osec.partition == partition)
314 return &osd->osec;
327 // If --compressed-debug-sections is specified, compress .debug_* sections.
330 sec->maybeCompress<ELFT>(ctx);
332 if (ctx.script->hasSectionsCommand)
333 ctx.script->allocateHeaders(ctx.mainPart->phdrs);
349 // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
354 // Handle --print-memory-usage option.
356 ctx.script->printMemoryUsage(ctx.e.outs());
381 // Backfill .note.gnu.build-id section content. This is done at last
388 if (auto e = buffer->commit())
389 Err(ctx) << "failed to write output '" << buffer->getPath()
402 Symbol &sym = file->getRelocTargetSym(rel);
411 // With --gc-sections, the field is already filled.
417 for (InputSectionBase *s : f->getSections()) {
421 if (isec->type == SHT_REL) {
422 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
423 } else if (isec->type == SHT_RELA) {
424 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
425 } else if (isec->type == SHT_CREL) {
428 for (Elf_Crel_Impl<true> r : RelocsCrel<true>(isec->content_)) {
429 Symbol &sym = file->getSymbol(r.r_symidx);
442 // If --emit-reloc or -r is given, preserve symbols referenced by relocations
453 sym.section->type == SHT_ARM_EXIDX)
463 // * --discard-locals is used.
468 (sym.section && (sym.section->flags & SHF_MERGE))))
476 SectionBase *sec = d->section;
479 assert(sec->isLive());
482 return s->getSectionPiece(d->value).live;
490 // - demote symbols defined relative to /DISCARD/ discarded input sections so
492 // - copy eligible symbols to .symTab
497 for (Symbol *b : file->getLocalSymbols()) {
498 assert(b->isLocal() && "should have been caught in initializeSymbols()");
503 if (dr->section && !dr->section->isLive())
507 ctx.in.symTab->addSymbol(b);
517 for (SectionCommand *cmd : ctx.script->sectionCommands) {
521 OutputSection &osec = osd->osec;
529 for (InputSectionBase *s : isd->sections) {
531 if (isStaticRelSecType(s->type))
536 // pointing to its contents if -r or --emit-reloc is given.
537 if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))
550 ctx.in.symTab->addSymbol(makeDefined(ctx, isec->file, "", STB_LOCAL,
556 // Today's loaders have a feature to make segments read-only after
565 if (sec->relro)
568 uint64_t flags = sec->flags;
570 // Non-allocatable or non-writable sections don't need RELRO because
572 // RELRO is for sections that are essentially read-only but need to
579 // for a thread-local storage. For each new thread, runtime
591 uint32_t type = sec->type;
599 if (ctx.in.got && sec == ctx.in.got->getParent())
602 // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
607 if (sec->name == ".toc")
612 // However, if "-z now" is given, the lazy symbol resolution is
614 if (sec == ctx.in.gotPlt->getParent())
617 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())
623 if (sec->name == ".dynamic")
630 StringRef s = sec->name;
668 // We want to put section specified by -T option first, so we
680 // order: R, RX, RXW, RW(RELRO), RW(non-RELRO).
682 // Read-only sections come first such that they go in the PT_LOAD covering the
695 // For -z lrodata-after-bss, place .lrodata after .lbss like GNU ld. This
697 // pressure for absolute relocations referencing small data from -fno-pic
711 // included in a truncate core file. In particular, .note.gnu.build-id, if
736 // For -z lrodata-after-bss, place .lbss/.lrodata/.ldata after .bss.
745 // Within TLS sections, or within other RelRo sections, or within non-RelRo
746 // sections, place non-NOBITS sections first.
755 // their coverage by a single signed 16-bit offset from the TOC base
786 const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
787 const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
789 if (a->sortRank != b->sortRank)
790 return a->sortRank < b->sortRank;
792 if (!(a->sortRank & RF_NOT_ADDR_SET))
793 return ctx.arg.sectionStartMap.lookup(a->name) <
794 ctx.arg.sectionStartMap.lookup(b->name);
802 p_align = std::max(p_align, sec->addralign);
804 sec->ptLoad = this;
807 // A statically linked position-dependent executable should only contain
822 name.replace(name.size() - 5, 5, "end");
837 if (!ctx.target->gotBaseSymInGotPlt)
840 ctx.sym.globalOffsetTable->section = sec;
848 ctx.sym.relaIpltStart->section = &dyn;
849 ctx.sym.relaIpltEnd->section = &dyn;
850 ctx.sym.relaIpltEnd->value = dyn.getSize();
857 return ctx.arg.emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
861 if (p->p_type != PT_LOAD)
864 if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
865 lastRO = p->lastSec;
870 // _etext is the first location after the last read-only loadable segment
873 ctx.sym.etext1->section = lastRO;
875 ctx.sym.etext2->section = lastRO;
879 // _edata points to the end of the last non-large mapped initialized
883 if (os->type != SHT_NOBITS && !isLarge(os))
885 if (os == last->lastSec)
890 ctx.sym.edata1->section = edata;
892 ctx.sym.edata2->section = edata;
896 ctx.sym.end1->section = last->lastSec;
898 ctx.sym.end2->section = last->lastSec;
902 // On RISC-V, set __bss_start to the start of .sbss if present.
905 ctx.sym.bss->section = sbss ? sbss : findSection(ctx, ".bss");
911 // Find GP-relative section with the lowest address
914 if (os->flags & SHF_MIPS_GPREL) {
915 ctx.sym.mipsGp->section = os;
916 ctx.sym.mipsGp->value = 0x7ff0;
929 return (osd && osd->osec.hasInputSections)
930 ? llvm::countl_zero(a->sortRank ^ osd->osec.sortRank)
931 : -1;
950 return assign->name != ".";
960 // Place non-alloc orphan sections at the end. This matches how we assign file
961 // offsets to non-alloc sections.
962 OutputSection *sec = &cast<OutputDesc>(*e)->osec;
963 if (!(sec->flags & SHF_ALLOC))
968 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent()) {
971 return assign->dataSegmentRelroEnd;
979 // value in the range [-1, 32] where [0, 32] indicates potential anchors (0:
980 // least similar; 32: identical). -1 means not an anchor.
989 (p == maxP && cast<OutputDesc>(*j)->osec.sortRank <= sec->sortRank)) {
999 return osd && osd->osec.hasInputSections;
1007 // making a read-only segment writable. If memory regions are defined, an
1011 ctx.script->hasPhdrsCommands() || !ctx.script->memoryRegions.empty();
1012 if (cast<OutputDesc>(*i)->osec.sortRank <= sec->sortRank || mustAfter) {
1021 for (; i != b; --i)
1022 if (isOutputSecWithInputSections(i[-1]))
1050 if (patAndSeed.first.match(sec->name))
1054 // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1065 if (patAndSeed.first.match(sec->name))
1079 // If both --symbol-ordering-file and call graph profile are present, the order
1099 int priority = -sectionOrder.size() - ctx.arg.symbolOrderingFile.size();
1108 SymbolOrderEntry &ent = it->second;
1114 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1123 for (Symbol *sym : ctx.symtab->getSymbols())
1127 for (Symbol *sym : file->getLocalSymbols())
1149 for (InputSection *isec : isd->sections) {
1151 totalSize += isec->getSize();
1155 unorderedSize += isec->getSize();
1158 orderedSections.push_back({isec, i->second});
1163 // section list. On targets with limited-range branches, this is the mid-point
1177 // only the first 8-16MB of the cold code (depending on which hot function it
1185 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1196 ctx.target->getThunkSectionSpacing() &&
1197 totalSize >= ctx.target->getThunkSectionSpacing()) {
1200 unorderedPos += unorderedSections[insPt]->getSize();
1206 isd->sections.clear();
1208 isd->sections.push_back(isec);
1210 isd->sections.push_back(p.first);
1212 isd->sections.push_back(isec);
1224 // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1232 if (ctx.script->hasSectionsCommand)
1240 // .toc is allocated just after .got and is accessed using GOT-relative
1242 // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1247 llvm::stable_sort(isd->sections,
1248 [](const InputSection *a, const InputSection *b) -> bool {
1249 return a->file->ppc64SmallCodeModelTocRelocs &&
1250 !b->file->ppc64SmallCodeModelTocRelocs;
1259 // Assign non-negative priorities due to --shuffle-sections.
1261 for (SectionCommand *cmd : ctx.script->sectionCommands)
1263 sortSection(ctx, osd->osec, order);
1269 // Don't sort if using -r. It is not necessary and we want to preserve the
1272 ctx.script->adjustOutputSections();
1278 for (SectionCommand *cmd : ctx.script->sectionCommands)
1280 osd->osec.sortRank = getSectionRank(ctx, osd->osec);
1281 if (!ctx.script->hasSectionsCommand) {
1285 ctx.script->sectionCommands.begin(), ctx.script->sectionCommands.end(),
1288 ctx.script->sectionCommands.begin(), mid,
1293 // point onwards the order of script->sectionCommands is fixed.
1294 ctx.script->processInsertCommands();
1295 ctx.script->adjustOutputSections();
1297 if (ctx.script->hasSectionsCommand)
1300 ctx.script->adjustSectionsAfterSorting();
1343 auto i = ctx.script->sectionCommands.begin();
1344 auto e = ctx.script->sectionCommands.end();
1347 return osd->osec.sectionIndex == UINT32_MAX;
1369 OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
1373 unsigned rank = orphan->sortRank;
1375 return cast<OutputDesc>(cmd)->osec.sortRank != rank;
1383 InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1384 InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1385 // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1386 // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1389 OutputSection *aOut = la->getParent();
1390 OutputSection *bOut = lb->getParent();
1393 return la->outSecOff < lb->outSecOff;
1394 if (aOut->addr == bOut->addr)
1395 return aOut->sectionIndex < bOut->sectionIndex;
1396 return aOut->addr < bOut->addr;
1402 if (!(sec->flags & SHF_LINK_ORDER))
1408 sec->type == SHT_ARM_EXIDX)
1415 for (SectionCommand *cmd : sec->commands) {
1422 for (InputSection *&isec : isd->sections) {
1423 if (isec->flags & SHF_LINK_ORDER) {
1424 InputSection *link = isec->getLinkOrderDep();
1425 if (link && !link->getParent())
1443 if (sec && sec->isNeeded() && sec->getParent()) {
1444 llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1445 sec->finalizeContents();
1450 StringRef s = sec->name;
1462 for (SectionCommand *bc : os->commands) {
1465 if (os->ptLoad != curPtLoad) {
1468 curPtLoad = os->ptLoad;
1470 for (InputSection *isec : isd->sections) {
1474 make<RandomizePaddingSection>(ctx, isec->addralign, os));
1477 isd->sections = std::move(tmp);
1491 ctx.script->assignAddresses();
1493 // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1494 // do require the relative addresses of OutputSections because linker scripts
1514 bool changed = ctx.target->needsThunks
1516 : ctx.target->relaxOnce(pass);
1517 bool spilled = ctx.script->spillSections();
1524 Err(ctx) << (ctx.target->needsThunks ? "thunk creation not converged"
1531 ctx.script->assignAddresses();
1536 ctx.script->assignAddresses();
1542 ctx.in.mipsGot->updateAllocSize(ctx);
1553 part.relrAuthDyn->relocs, [this, &part](const RelativeReloc &elem) {
1554 const Relocation &reloc = elem.inputSec->relocs()[elem.relocIdx];
1555 if (isInt<32>(reloc.sym->getVA(ctx, reloc.addend)))
1557 part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, elem.inputSec,
1563 changed |= (it != part.relrAuthDyn->relocs.end());
1564 part.relrAuthDyn->relocs.erase(it, part.relrAuthDyn->relocs.end());
1567 changed |= part.relaDyn->updateAllocSize(ctx);
1569 changed |= part.relrDyn->updateAllocSize(ctx);
1571 changed |= part.relrAuthDyn->updateAllocSize(ctx);
1573 changed |= part.memtagGlobalDescriptors->updateAllocSize(ctx);
1577 ctx.script->assignAddresses();
1586 Err(ctx) << "address (0x" << Twine::utohexstr(changes.first->addr)
1587 << ") of section '" << changes.first->name
1600 ctx.target->finalizeRelax(pass);
1604 sec->addr = 0;
1607 // Warn because this is error-prone.
1608 for (SectionCommand *cmd : ctx.script->sectionCommands)
1610 OutputSection *osec = &osd->osec;
1611 if (osec->addr % osec->addralign != 0)
1612 Warn(ctx) << "address (0x" << Twine::utohexstr(osec->addr)
1613 << ") of section " << osec->name
1614 << " is not a multiple of alignment (" << osec->addralign
1620 ctx.script->erasePotentialSpillSections();
1629 parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1634 const SectionBase *sec = def->section;
1639 if (!inputSec || !inputSec->bytesDropped)
1642 const size_t OldSize = inputSec->content().size();
1643 const size_t NewSize = OldSize - inputSec->bytesDropped;
1645 if (def->value > NewSize && def->value <= OldSize) {
1647 << "Moving symbol " << Sym->getName() << " from "
1648 << def->value << " to "
1649 << def->value - inputSec->bytesDropped << " bytes\n");
1650 def->value -= inputSec->bytesDropped;
1654 if (def->value + def->size > NewSize && def->value <= OldSize &&
1655 def->value + def->size <= OldSize) {
1657 << "Shrinking symbol " << Sym->getName() << " from "
1658 << def->size << " to " << def->size - inputSec->bytesDropped
1660 def->size -= inputSec->bytesDropped;
1668 // relaxation pass does that. It is only enabled when --optimize-bb-jumps
1674 ctx.script->assignAddresses();
1682 if (!(osec->flags & SHF_EXECINSTR))
1692 numDeleted += ctx.target->deleteFallThruJmpInsn(sec, sec.file, next);
1695 ctx.script->assignAddresses();
1705 is->trim();
1708 // In order to allow users to manipulate linker-synthesized sections,
1723 // after a non-synthetic one which will be our starting point.
1734 if (sec->getParent() && sec->isNeeded())
1741 sec == ctx.mainPart->relaDyn.get())
1751 if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
1752 for (SectionCommand *cmd : osec->commands)
1754 llvm::erase_if(isd->sections, [&](InputSection *isec) {
1757 llvm::erase_if(ctx.script->orphanSections, [&](const InputSectionBase *sec) {
1773 for (SectionCommand *cmd : ctx.script->sectionCommands)
1775 addStartStopSymbols(osd->osec);
1780 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1781 if (ctx.mainPart->dynamic->parent) {
1782 Symbol *s = ctx.symtab->addSymbol(Defined{
1784 /*value=*/0, /*size=*/0, ctx.mainPart->dynamic.get()});
1785 s->isUsedInRegularObj = true;
1791 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1804 Symbol *s = ctx.symtab->find("__global_pointer$");
1805 if (s && s->isDefined())
1817 // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address
1823 Symbol *s = ctx.symtab->find("_TLS_MODULE_BASE_");
1824 if (s && s->isUndefined()) {
1825 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
1842 // If the previous code block defines any non-hidden symbols (e.g.
1846 sym->isExported = sym->includeInDynsym(ctx);
1857 // Change values of linker-script-defined symbols from placeholders (assigned
1859 ctx.script->processSymbolAssignments();
1866 // a linker-script-defined symbol is absolute.
1871 if (ctx.in.plt && ctx.in.plt->isNeeded())
1872 ctx.in.plt->addSymbols();
1873 if (ctx.in.iplt && ctx.in.iplt->isNeeded())
1874 ctx.in.iplt->addSymbols();
1897 llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1898 return ctx.symtab->soNames.count(CachedHashStringRef(needed));
1902 for (Symbol *sym : file->requiredSymbols) {
1903 if (sym->dsoDefined)
1905 if (sym->isUndefined() && !sym->isWeak()) {
1908 << file << " (disallowed by --no-allow-shlib-undefined)";
1909 } else if (sym->isDefined() &&
1910 sym->computeBinding(ctx) == STB_LOCAL) {
1912 << "non-exported symbol '" << sym << "' in '" << sym->file
1922 // Now that we have defined all possible global symbols including linker-
1924 for (Symbol *sym : ctx.symtab->getSymbols()) {
1925 if (!sym->isUsedInRegularObj || !includeInSymtab(ctx, *sym))
1928 sym->binding = sym->computeBinding(ctx);
1930 ctx.in.symTab->addSymbol(sym);
1932 // computeBinding might localize a linker-synthesized hidden symbol
1934 if (sym->isExported && !sym->isLocal()) {
1935 ctx.partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1936 if (auto *file = dyn_cast<SharedFile>(sym->file))
1937 if (file->isNeeded && !sym->isUndefined())
1947 for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1949 for (DynamicReloc &reloc : part.relaDyn->relocs)
1952 part.dynSymTab->addSymbol(reloc.sym);
1957 ctx.in.mipsGot->build();
1960 ctx.script->diagnoseOrphanHandling();
1961 ctx.script->diagnoseMissingSGSectionAddress();
1966 // ctx.in.shStrTab. If -z nosectionheader is specified, drop non-ALLOC
1968 for (SectionCommand *cmd : ctx.script->sectionCommands)
1970 OutputSection *osec = &osd->osec;
1971 if (!ctx.in.shStrTab && !(osec->flags & SHF_ALLOC))
1974 osec->sectionIndex = ctx.outputSections.size();
1976 osec->shName = ctx.in.shStrTab->addString(osec->name);
1981 auto i = ctx.arg.sectionStartMap.find(sec->name);
1983 sec->addrExpr = [=] { return i->second; };
1991 ctx.symtab->addSymbol(Undefined{ctx.internalFile, "__tls_get_addr",
1993 sym->isPreemptible = true;
1994 ctx.partitions[0].dynSymTab->addSymbol(sym);
2000 ctx.out.elfHeader->sectionIndex = 1;
2001 ctx.out.elfHeader->size = sizeof(typename ELFT::Ehdr);
2008 part.phdrs = ctx.script->hasPhdrsCommands() ? ctx.script->createPhdrs()
2015 // Add separate segments for MIPS-specific sections.
2024 ctx.out.programHeaders->size =
2025 sizeof(Elf_Phdr) * ctx.mainPart->phdrs.size();
2031 for (auto &p : ctx.mainPart->phdrs)
2032 if (p->p_type == PT_TLS)
2040 if (ctx.script->noCrossRefs.size()) {
2067 part.relaDyn->mergeRels();
2069 part.relaDyn->partitionRels();
2073 part.relrDyn->mergeRels();
2077 part.relrAuthDyn->mergeRels();
2092 if (!ctx.script->hasSectionsCommand && !ctx.arg.relocatable)
2098 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2099 // JAL instruction can target only +-1 MiB from PC. It is a linker's
2132 // Relaxation to delete inter-basic block jumps created by basic block
2142 sec->finalize(ctx);
2144 ctx.script->checkFinalScriptConditions();
2153 // --execute-only is used. --execute-only make pages executable but not
2161 if (osec->flags & SHF_EXECINSTR)
2163 if (!(isec->flags & SHF_EXECINSTR))
2164 ErrAlways(ctx) << "cannot place " << isec << " into " << osec->name
2165 << ": --execute-only does not support intermingling "
2181 Defined *stopSym = addOptionalRegular(ctx, end, os, -1);
2183 os->usedInExpression = true;
2213 Defined *stopSym = addOptionalRegular(ctx, ss.save("__stop_" + s), &osec, -1,
2220 if (!(sec->flags & SHF_ALLOC))
2226 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2246 auto addHdr = [&, &ctx = ctx](unsigned type, unsigned flags) -> PhdrEntry * {
2264 addHdr(PT_PHDR, PF_R)->add(ctx.out.programHeaders.get());
2266 addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2270 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2277 load->add(ctx.out.elfHeader.get());
2278 load->add(ctx.out.programHeaders.get());
2283 // read-only by dynamic linker after processing relocations.
2290 if (sec->partition != partNo || !needsPtLoad(sec))
2295 relRo->add(sec);
2297 ErrAlways(ctx) << "section: " << sec->name
2304 relRo->p_align = 1;
2316 if (sec->partition != partNo) {
2317 if (isMain && sec->partition == 255)
2318 addHdr(PT_LOAD, computeFlags(ctx, sec->getPhdrFlags()))->add(sec);
2333 // not-NOBITS section after a NOBITS, we create a new LOAD for the latter
2334 // even if flags match, so as not to require actually writing the
2335 // supposed-to-be-NOBITS section to the output file. (However, we cannot do
2338 uint64_t newFlags = computeFlags(ctx, sec->getPhdrFlags());
2339 // When --no-rosegment is specified, RO and RX sections are compatible.
2347 load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2349 sec->memRegion == load->firstSec->memRegion &&
2350 (sameLMARegion || load->lastSec == ctx.out.programHeaders.get()) &&
2351 (ctx.script->hasSectionsCommand || sec->type == SHT_NOBITS ||
2352 load->lastSec->type != SHT_NOBITS)) {
2353 load->p_flags |= newFlags;
2359 load->add(sec);
2365 if (sec->partition == partNo && sec->flags & SHF_TLS)
2366 tlsHdr->add(sec);
2367 if (tlsHdr->firstSec)
2371 if (OutputSection *sec = part.dynamic->getParent())
2372 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2374 if (relRo->firstSec)
2378 if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2379 part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2380 addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2381 ->add(part.ehFrameHdr->getParent());
2387 addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
2392 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2397 addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
2402 // pages for the stack non-executable. If you really want an executable
2403 // stack, you can pass -z execstack, but that's not recommended for
2408 addHdr(PT_GNU_STACK, perm)->p_memsz = ctx.arg.zStackSize;
2411 // PT_OPENBSD_NOBTCFI is an OpenBSD-specific header to mark that the
2412 // executable is expected to violate branch-target CFI checks.
2416 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2424 addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2430 if (sec->partition != partNo)
2432 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2433 if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2435 note->add(sec);
2448 return cmd->partition == partNo && cmd->type == shType;
2454 entry->add(*i);
2463 auto pageAlign = [&, &ctx = this->ctx](const PhdrEntry *p) {
2464 OutputSection *cmd = p->firstSec;
2467 cmd->alignExpr = [align = cmd->addralign]() { return align; };
2468 if (!cmd->addrExpr) {
2472 // When -z separate-code is used we must not have any overlap in pages
2473 // between an executable segment and a non-executable segment. We align to
2475 // and non-executable segments.
2484 (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2485 cmd->type == SHT_LLVM_PART_EHDR)
2486 cmd->addrExpr = [&ctx = this->ctx] {
2487 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize);
2498 // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2502 else if (ctx.tlsPhdr && ctx.tlsPhdr->firstSec == p->firstSec)
2503 cmd->addrExpr = [&ctx] {
2504 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2505 alignToPowerOf2(ctx.script->getDot() % ctx.arg.maxPageSize,
2506 ctx.tlsPhdr->p_align);
2509 cmd->addrExpr = [&ctx] {
2510 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2511 ctx.script->getDot() % ctx.arg.maxPageSize;
2519 if (p->p_type == PT_LOAD && p->firstSec) {
2526 // Compute an in-file position for a given section. The file offset must be the
2532 if (os->ptLoad && os->ptLoad->firstSec == os)
2533 return alignTo(off, os->ptLoad->p_align, os->addr);
2538 if (os->type == SHT_NOBITS && (!ctx.tlsPhdr || ctx.tlsPhdr->firstSec != os))
2542 if (!os->ptLoad)
2543 return alignToPowerOf2(off, os->addralign);
2546 // using this formula: Off2 = Off1 + (VA2 - VA1).
2547 OutputSection *first = os->ptLoad->firstSec;
2548 return first->offset + os->addr - first->addr;
2552 // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2559 sec->offset = sec->getLMA();
2560 minAddr = std::min(minAddr, sec->offset);
2567 sec->offset -= minAddr;
2568 fileSize = std::max(fileSize, sec->offset + sec->size);
2573 return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2578 ctx.out.programHeaders->offset = ctx.out.elfHeader->size;
2579 uint64_t off = ctx.out.elfHeader->size + ctx.out.programHeaders->size;
2584 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2587 // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2590 if (!(sec->flags & SHF_ALLOC))
2593 sec->offset = off;
2594 if (sec->type != SHT_NOBITS)
2595 off += sec->size;
2599 // following section to avoid loading non-segments parts of the file.
2601 lastRX->lastSec == sec)
2605 if (osec->flags & SHF_ALLOC)
2607 osec->offset = alignToPowerOf2(off, osec->addralign);
2608 off = osec->offset + osec->size;
2622 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2625 if (sec->type == SHT_NOBITS)
2627 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2628 ErrAlways(ctx) << "unable to place section " << sec->name
2630 << rangeToString(sec->offset, sec->size)
2639 OutputSection *first = p->firstSec;
2640 OutputSection *last = p->lastSec;
2645 if (part.armExidx && p->p_type == PT_ARM_EXIDX) {
2646 p->p_filesz = part.armExidx->getSize();
2647 p->p_memsz = p->p_filesz;
2648 p->p_offset = first->offset + part.armExidx->outSecOff;
2649 p->p_vaddr = first->addr + part.armExidx->outSecOff;
2650 p->p_align = part.armExidx->addralign;
2652 p->p_offset -= part.elfHeader->getParent()->offset;
2654 if (!p->hasLMA)
2655 p->p_paddr = first->getLMA() + part.armExidx->outSecOff;
2660 p->p_filesz = last->offset - first->offset;
2661 if (last->type != SHT_NOBITS)
2662 p->p_filesz += last->size;
2664 p->p_memsz = last->addr + last->size - first->addr;
2665 p->p_offset = first->offset;
2666 p->p_vaddr = first->addr;
2671 p->p_offset -= part.elfHeader->getParent()->offset;
2673 if (!p->hasLMA)
2674 p->p_paddr = first->getLMA();
2699 SectionOffset a = sections[i - 1];
2701 if (b.offset >= a.offset + a.sec->size)
2706 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2709 Err(ctx) << "section " << a.sec->name << " " << name
2710 << " range overlaps with " << b.sec->name << "\n>>> "
2711 << a.sec->name << " range is "
2712 << rangeToString(a.offset, a.sec->size) << "\n>>> " << b.sec->name
2713 << " range is " << rangeToString(b.offset, b.sec->size);
2725 if ((os->addr + os->size < os->addr) ||
2726 (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2727 Err(ctx) << "section " << os->name << " at 0x"
2728 << utohexstr(os->addr, true) << " of size 0x"
2729 << utohexstr(os->size, true)
2734 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2736 // file so we skip any non-allocated sections in that case.
2739 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2740 (!ctx.arg.oFormatBinary || (sec->flags & SHF_ALLOC)))
2741 fileOffs.push_back({sec, sec->offset});
2744 // When linking with -r there is no need to check for overlapping virtual/load
2757 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2758 vmas.push_back({sec, sec->addr});
2766 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2767 lmas.push_back({sec, sec->getLMA()});
2773 // 1. the '-e' entry command-line option;
2780 if (Symbol *b = ctx.symtab->find(ctx.arg.entry))
2781 return b->getVA(ctx);
2808 eHdr->e_type = getELFType(ctx);
2809 eHdr->e_entry = getEntryAddr(ctx);
2811 // If -z nosectionheader is specified, omit the section header table.
2814 eHdr->e_shoff = sectionHeaderOff;
2825 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(ctx.bufferStart + eHdr->e_shoff);
2828 sHdrs->sh_size = num;
2830 eHdr->e_shnum = num;
2832 uint32_t strTabIndex = ctx.in.shStrTab->getParent()->sectionIndex;
2834 sHdrs->sh_link = strTabIndex;
2835 eHdr->e_shstrndx = SHN_XINDEX;
2837 eHdr->e_shstrndx = strTabIndex;
2841 sec->writeHeaderTo<ELFT>(++sHdrs);
2853 s << os->name << ' ' << os->size << "\n";
2873 ctx.bufferStart = buffer->getBufferStart();
2879 if (sec->flags & SHF_ALLOC)
2880 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2893 // We'll leave other pages in segments as-is because the rest will be
2899 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2901 ctx.target->trapInstr,
2902 ctx.bufferStart + alignDown(p->firstSec->offset + p->p_filesz, 4),
2903 ctx.bufferStart + alignToPowerOf2(p->firstSec->offset + p->p_filesz,
2911 if (p->p_type == PT_LOAD)
2914 if (last && (last->p_flags & PF_X))
2915 last->p_memsz = last->p_filesz =
2916 alignToPowerOf2(last->p_filesz, ctx.arg.maxPageSize);
2925 // In -r or --emit-relocs mode, write the relocation sections first as in
2930 if (isStaticRelSecType(sec->type))
2931 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2936 if (!isStaticRelSecType(sec->type))
2937 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2943 if (isStaticRelSecType(sec->type))
2944 sec->checkDynRelAddends(ctx);
2958 std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2962 hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2966 hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
2970 if (!ctx.mainPart->buildId || !ctx.mainPart->buildId->getParent())
2975 part.buildId->writeBuildId(ctx.arg.buildIdVector);
2980 size_t hashSize = ctx.mainPart->buildId->hashSize;
2988 // (second-)preimage and collision resistance. In practice people use 'md5'
3015 part.buildId->writeBuildId(output);