[mlir][py] Enable loading only specified dialects during creation. (#121421)
[llvm-project.git] / lld / ELF / Writer.cpp
blob3e92b7653e31aff598f4fb84ca9a3fc3c9855c42
1 //===- Writer.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 //===----------------------------------------------------------------------===//
9 #include "Writer.h"
10 #include "AArch64ErrataFix.h"
11 #include "ARMErrataFix.h"
12 #include "CallGraphSort.h"
13 #include "Config.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
16 #include "MapFile.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Arrays.h"
24 #include "lld/Common/CommonLinkerContext.h"
25 #include "lld/Common/Filesystem.h"
26 #include "lld/Common/Strings.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/Support/BLAKE3.h"
30 #include "llvm/Support/Parallel.h"
31 #include "llvm/Support/RandomNumberGenerator.h"
32 #include "llvm/Support/TimeProfiler.h"
33 #include "llvm/Support/xxhash.h"
34 #include <climits>
36 #define DEBUG_TYPE "lld"
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::object;
41 using namespace llvm::support;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::elf;
46 namespace {
47 // The writer writes a SymbolTable result to a file.
48 template <class ELFT> class Writer {
49 public:
50 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
52 Writer(Ctx &ctx) : ctx(ctx), buffer(ctx.e.outputBuffer), tc(ctx) {}
54 void run();
56 private:
57 void addSectionSymbols();
58 void sortSections();
59 void resolveShfLinkOrder();
60 void finalizeAddressDependentContent();
61 void optimizeBasicBlockJumps();
62 void sortInputSections();
63 void sortOrphanSections();
64 void finalizeSections();
65 void checkExecuteOnly();
66 void setReservedSymbolSections();
68 SmallVector<std::unique_ptr<PhdrEntry>, 0> createPhdrs(Partition &part);
69 void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
70 unsigned pFlags);
71 void assignFileOffsets();
72 void assignFileOffsetsBinary();
73 void setPhdrs(Partition &part);
74 void checkSections();
75 void fixSectionAlignments();
76 void openFile();
77 void writeTrapInstr();
78 void writeHeader();
79 void writeSections();
80 void writeSectionsBinary();
81 void writeBuildId();
83 Ctx &ctx;
84 std::unique_ptr<FileOutputBuffer> &buffer;
85 // ThunkCreator holds Thunks that are used at writeTo time.
86 ThunkCreator tc;
88 void addRelIpltSymbols();
89 void addStartEndSymbols();
90 void addStartStopSymbols(OutputSection &osec);
92 uint64_t fileSize;
93 uint64_t sectionHeaderOff;
95 } // anonymous namespace
97 template <class ELFT> void elf::writeResult(Ctx &ctx) {
98 Writer<ELFT>(ctx).run();
101 static void
102 removeEmptyPTLoad(Ctx &ctx, SmallVector<std::unique_ptr<PhdrEntry>, 0> &phdrs) {
103 auto it = std::stable_partition(phdrs.begin(), phdrs.end(), [&](auto &p) {
104 if (p->p_type != PT_LOAD)
105 return true;
106 if (!p->firstSec)
107 return false;
108 uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
109 return size != 0;
112 // Clear OutputSection::ptLoad for sections contained in removed
113 // segments.
114 DenseSet<PhdrEntry *> removed;
115 for (auto it2 = it; it2 != phdrs.end(); ++it2)
116 removed.insert(it2->get());
117 for (OutputSection *sec : ctx.outputSections)
118 if (removed.count(sec->ptLoad))
119 sec->ptLoad = nullptr;
120 phdrs.erase(it, phdrs.end());
123 void elf::copySectionsIntoPartitions(Ctx &ctx) {
124 SmallVector<InputSectionBase *, 0> newSections;
125 const size_t ehSize = ctx.ehInputSections.size();
126 for (unsigned part = 2; part != ctx.partitions.size() + 1; ++part) {
127 for (InputSectionBase *s : ctx.inputSections) {
128 if (!(s->flags & SHF_ALLOC) || !s->isLive() || s->type != SHT_NOTE)
129 continue;
130 auto *copy = make<InputSection>(cast<InputSection>(*s));
131 copy->partition = part;
132 newSections.push_back(copy);
134 for (size_t i = 0; i != ehSize; ++i) {
135 assert(ctx.ehInputSections[i]->isLive());
136 auto *copy = make<EhInputSection>(*ctx.ehInputSections[i]);
137 copy->partition = part;
138 ctx.ehInputSections.push_back(copy);
142 ctx.inputSections.insert(ctx.inputSections.end(), newSections.begin(),
143 newSections.end());
146 static Defined *addOptionalRegular(Ctx &ctx, StringRef name, SectionBase *sec,
147 uint64_t val, uint8_t stOther = STV_HIDDEN) {
148 Symbol *s = ctx.symtab->find(name);
149 if (!s || s->isDefined() || s->isCommon())
150 return nullptr;
152 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
153 stOther, STT_NOTYPE, val,
154 /*size=*/0, sec});
155 s->isUsedInRegularObj = true;
156 return cast<Defined>(s);
159 // The linker is expected to define some symbols depending on
160 // the linking result. This function defines such symbols.
161 void elf::addReservedSymbols(Ctx &ctx) {
162 if (ctx.arg.emachine == EM_MIPS) {
163 auto addAbsolute = [&](StringRef name) {
164 Symbol *sym =
165 ctx.symtab->addSymbol(Defined{ctx, ctx.internalFile, name, STB_GLOBAL,
166 STV_HIDDEN, STT_NOTYPE, 0, 0, nullptr});
167 sym->isUsedInRegularObj = true;
168 return cast<Defined>(sym);
170 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
171 // so that it points to an absolute address which by default is relative
172 // to GOT. Default offset is 0x7ff0.
173 // See "Global Data Symbols" in Chapter 6 in the following document:
174 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
175 ctx.sym.mipsGp = addAbsolute("_gp");
177 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
178 // start of function and 'gp' pointer into GOT.
179 if (ctx.symtab->find("_gp_disp"))
180 ctx.sym.mipsGpDisp = addAbsolute("_gp_disp");
182 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
183 // pointer. This symbol is used in the code generated by .cpload pseudo-op
184 // in case of using -mno-shared option.
185 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
186 if (ctx.symtab->find("__gnu_local_gp"))
187 ctx.sym.mipsLocalGp = addAbsolute("__gnu_local_gp");
188 } else if (ctx.arg.emachine == EM_PPC) {
189 // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
190 // support Small Data Area, define it arbitrarily as 0.
191 addOptionalRegular(ctx, "_SDA_BASE_", nullptr, 0, STV_HIDDEN);
192 } else if (ctx.arg.emachine == EM_PPC64) {
193 addPPC64SaveRestore(ctx);
196 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
197 // combines the typical ELF GOT with the small data sections. It commonly
198 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
199 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
200 // represent the TOC base which is offset by 0x8000 bytes from the start of
201 // the .got section.
202 // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
203 // correctness of some relocations depends on its value.
204 StringRef gotSymName =
205 (ctx.arg.emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
207 if (Symbol *s = ctx.symtab->find(gotSymName)) {
208 if (s->isDefined()) {
209 ErrAlways(ctx) << s->file << " cannot redefine linker defined symbol '"
210 << gotSymName << "'";
211 return;
214 uint64_t gotOff = 0;
215 if (ctx.arg.emachine == EM_PPC64)
216 gotOff = 0x8000;
218 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
219 STV_HIDDEN, STT_NOTYPE, gotOff, /*size=*/0,
220 ctx.out.elfHeader.get()});
221 ctx.sym.globalOffsetTable = cast<Defined>(s);
224 // __ehdr_start is the location of ELF file headers. Note that we define
225 // this symbol unconditionally even when using a linker script, which
226 // differs from the behavior implemented by GNU linker which only define
227 // this symbol if ELF headers are in the memory mapped segment.
228 addOptionalRegular(ctx, "__ehdr_start", ctx.out.elfHeader.get(), 0,
229 STV_HIDDEN);
231 // __executable_start is not documented, but the expectation of at
232 // least the Android libc is that it points to the ELF header.
233 addOptionalRegular(ctx, "__executable_start", ctx.out.elfHeader.get(), 0,
234 STV_HIDDEN);
236 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
237 // each DSO. The address of the symbol doesn't matter as long as they are
238 // different in different DSOs, so we chose the start address of the DSO.
239 addOptionalRegular(ctx, "__dso_handle", ctx.out.elfHeader.get(), 0,
240 STV_HIDDEN);
242 // If linker script do layout we do not need to create any standard symbols.
243 if (ctx.script->hasSectionsCommand)
244 return;
246 auto add = [&](StringRef s, int64_t pos) {
247 return addOptionalRegular(ctx, s, ctx.out.elfHeader.get(), pos,
248 STV_DEFAULT);
251 ctx.sym.bss = add("__bss_start", 0);
252 ctx.sym.end1 = add("end", -1);
253 ctx.sym.end2 = add("_end", -1);
254 ctx.sym.etext1 = add("etext", -1);
255 ctx.sym.etext2 = add("_etext", -1);
256 ctx.sym.edata1 = add("edata", -1);
257 ctx.sym.edata2 = add("_edata", -1);
260 static void demoteDefined(Defined &sym, DenseMap<SectionBase *, size_t> &map) {
261 if (map.empty())
262 for (auto [i, sec] : llvm::enumerate(sym.file->getSections()))
263 map.try_emplace(sec, i);
264 // Change WEAK to GLOBAL so that if a scanned relocation references sym,
265 // maybeReportUndefined will report an error.
266 uint8_t binding = sym.isWeak() ? uint8_t(STB_GLOBAL) : sym.binding;
267 Undefined(sym.file, sym.getName(), binding, sym.stOther, sym.type,
268 /*discardedSecIdx=*/map.lookup(sym.section))
269 .overwrite(sym);
270 // Eliminate from the symbol table, otherwise we would leave an undefined
271 // symbol if the symbol is unreferenced in the absence of GC.
272 sym.isUsedInRegularObj = false;
275 // If all references to a DSO happen to be weak, the DSO is not added to
276 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid
277 // dangling references to an unneeded DSO. Use a weak binding to avoid
278 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
280 // In addition, demote symbols defined in discarded sections, so that
281 // references to /DISCARD/ discarded symbols will lead to errors.
282 static void demoteSymbolsAndComputeIsPreemptible(Ctx &ctx) {
283 llvm::TimeTraceScope timeScope("Demote symbols");
284 DenseMap<InputFile *, DenseMap<SectionBase *, size_t>> sectionIndexMap;
285 for (Symbol *sym : ctx.symtab->getSymbols()) {
286 if (auto *d = dyn_cast<Defined>(sym)) {
287 if (d->section && !d->section->isLive())
288 demoteDefined(*d, sectionIndexMap[d->file]);
289 } else {
290 auto *s = dyn_cast<SharedSymbol>(sym);
291 if (sym->isLazy() || (s && !cast<SharedFile>(s->file)->isNeeded)) {
292 uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
293 Undefined(ctx.internalFile, sym->getName(), binding, sym->stOther,
294 sym->type)
295 .overwrite(*sym);
296 sym->versionId = VER_NDX_GLOBAL;
300 sym->isExported = sym->includeInDynsym(ctx);
301 if (ctx.arg.hasDynSymTab)
302 sym->isPreemptible = sym->isExported && computeIsPreemptible(ctx, *sym);
306 static OutputSection *findSection(Ctx &ctx, StringRef name,
307 unsigned partition = 1) {
308 for (SectionCommand *cmd : ctx.script->sectionCommands)
309 if (auto *osd = dyn_cast<OutputDesc>(cmd))
310 if (osd->osec.name == name && osd->osec.partition == partition)
311 return &osd->osec;
312 return nullptr;
315 // The main function of the writer.
316 template <class ELFT> void Writer<ELFT>::run() {
317 // Now that we have a complete set of output sections. This function
318 // completes section contents. For example, we need to add strings
319 // to the string table, and add entries to .got and .plt.
320 // finalizeSections does that.
321 finalizeSections();
322 checkExecuteOnly();
324 // If --compressed-debug-sections is specified, compress .debug_* sections.
325 // Do it right now because it changes the size of output sections.
326 for (OutputSection *sec : ctx.outputSections)
327 sec->maybeCompress<ELFT>(ctx);
329 if (ctx.script->hasSectionsCommand)
330 ctx.script->allocateHeaders(ctx.mainPart->phdrs);
332 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
333 // 0 sized region. This has to be done late since only after assignAddresses
334 // we know the size of the sections.
335 for (Partition &part : ctx.partitions)
336 removeEmptyPTLoad(ctx, part.phdrs);
338 if (!ctx.arg.oFormatBinary)
339 assignFileOffsets();
340 else
341 assignFileOffsetsBinary();
343 for (Partition &part : ctx.partitions)
344 setPhdrs(part);
346 // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
347 // because the files may be useful in case checkSections() or openFile()
348 // fails, for example, due to an erroneous file size.
349 writeMapAndCref(ctx);
351 // Handle --print-memory-usage option.
352 if (ctx.arg.printMemoryUsage)
353 ctx.script->printMemoryUsage(ctx.e.outs());
355 if (ctx.arg.checkSections)
356 checkSections();
358 // It does not make sense try to open the file if we have error already.
359 if (errCount(ctx))
360 return;
363 llvm::TimeTraceScope timeScope("Write output file");
364 // Write the result down to a file.
365 openFile();
366 if (errCount(ctx))
367 return;
369 if (!ctx.arg.oFormatBinary) {
370 if (ctx.arg.zSeparate != SeparateSegmentKind::None)
371 writeTrapInstr();
372 writeHeader();
373 writeSections();
374 } else {
375 writeSectionsBinary();
378 // Backfill .note.gnu.build-id section content. This is done at last
379 // because the content is usually a hash value of the entire output file.
380 writeBuildId();
381 if (errCount(ctx))
382 return;
384 if (auto e = buffer->commit())
385 Err(ctx) << "failed to write output '" << buffer->getPath()
386 << "': " << std::move(e);
388 if (!ctx.arg.cmseOutputLib.empty())
389 writeARMCmseImportLib<ELFT>(ctx);
393 template <class ELFT, class RelTy>
394 static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
395 llvm::ArrayRef<RelTy> rels) {
396 for (const RelTy &rel : rels) {
397 Symbol &sym = file->getRelocTargetSym(rel);
398 if (sym.isLocal())
399 sym.used = true;
403 // The function ensures that the "used" field of local symbols reflects the fact
404 // that the symbol is used in a relocation from a live section.
405 template <class ELFT> static void markUsedLocalSymbols(Ctx &ctx) {
406 // With --gc-sections, the field is already filled.
407 // See MarkLive<ELFT>::resolveReloc().
408 if (ctx.arg.gcSections)
409 return;
410 for (ELFFileBase *file : ctx.objectFiles) {
411 ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
412 for (InputSectionBase *s : f->getSections()) {
413 InputSection *isec = dyn_cast_or_null<InputSection>(s);
414 if (!isec)
415 continue;
416 if (isec->type == SHT_REL) {
417 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
418 } else if (isec->type == SHT_RELA) {
419 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
420 } else if (isec->type == SHT_CREL) {
421 // The is64=true variant also works with ELF32 since only the r_symidx
422 // member is used.
423 for (Elf_Crel_Impl<true> r : RelocsCrel<true>(isec->content_)) {
424 Symbol &sym = file->getSymbol(r.r_symidx);
425 if (sym.isLocal())
426 sym.used = true;
433 static bool shouldKeepInSymtab(Ctx &ctx, const Defined &sym) {
434 if (sym.isSection())
435 return false;
437 // If --emit-reloc or -r is given, preserve symbols referenced by relocations
438 // from live sections.
439 if (sym.used && ctx.arg.copyRelocs)
440 return true;
442 // Exclude local symbols pointing to .ARM.exidx sections.
443 // They are probably mapping symbols "$d", which are optional for these
444 // sections. After merging the .ARM.exidx sections, some of these symbols
445 // may become dangling. The easiest way to avoid the issue is not to add
446 // them to the symbol table from the beginning.
447 if (ctx.arg.emachine == EM_ARM && sym.section &&
448 sym.section->type == SHT_ARM_EXIDX)
449 return false;
451 if (ctx.arg.discard == DiscardPolicy::None)
452 return true;
453 if (ctx.arg.discard == DiscardPolicy::All)
454 return false;
456 // In ELF assembly .L symbols are normally discarded by the assembler.
457 // If the assembler fails to do so, the linker discards them if
458 // * --discard-locals is used.
459 // * The symbol is in a SHF_MERGE section, which is normally the reason for
460 // the assembler keeping the .L symbol.
461 if (sym.getName().starts_with(".L") &&
462 (ctx.arg.discard == DiscardPolicy::Locals ||
463 (sym.section && (sym.section->flags & SHF_MERGE))))
464 return false;
465 return true;
468 bool elf::includeInSymtab(Ctx &ctx, const Symbol &b) {
469 if (auto *d = dyn_cast<Defined>(&b)) {
470 // Always include absolute symbols.
471 SectionBase *sec = d->section;
472 if (!sec)
473 return true;
474 assert(sec->isLive());
476 if (auto *s = dyn_cast<MergeInputSection>(sec))
477 return s->getSectionPiece(d->value).live;
478 return true;
480 return b.used || !ctx.arg.gcSections;
483 // Scan local symbols to:
485 // - demote symbols defined relative to /DISCARD/ discarded input sections so
486 // that relocations referencing them will lead to errors.
487 // - copy eligible symbols to .symTab
488 static void demoteAndCopyLocalSymbols(Ctx &ctx) {
489 llvm::TimeTraceScope timeScope("Add local symbols");
490 for (ELFFileBase *file : ctx.objectFiles) {
491 DenseMap<SectionBase *, size_t> sectionIndexMap;
492 for (Symbol *b : file->getLocalSymbols()) {
493 assert(b->isLocal() && "should have been caught in initializeSymbols()");
494 auto *dr = dyn_cast<Defined>(b);
495 if (!dr)
496 continue;
498 if (dr->section && !dr->section->isLive())
499 demoteDefined(*dr, sectionIndexMap);
500 else if (ctx.in.symTab && includeInSymtab(ctx, *b) &&
501 shouldKeepInSymtab(ctx, *dr))
502 ctx.in.symTab->addSymbol(b);
507 // Create a section symbol for each output section so that we can represent
508 // relocations that point to the section. If we know that no relocation is
509 // referring to a section (that happens if the section is a synthetic one), we
510 // don't create a section symbol for that section.
511 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
512 for (SectionCommand *cmd : ctx.script->sectionCommands) {
513 auto *osd = dyn_cast<OutputDesc>(cmd);
514 if (!osd)
515 continue;
516 OutputSection &osec = osd->osec;
517 InputSectionBase *isec = nullptr;
518 // Iterate over all input sections and add a STT_SECTION symbol if any input
519 // section may be a relocation target.
520 for (SectionCommand *cmd : osec.commands) {
521 auto *isd = dyn_cast<InputSectionDescription>(cmd);
522 if (!isd)
523 continue;
524 for (InputSectionBase *s : isd->sections) {
525 // Relocations are not using REL[A] section symbols.
526 if (isStaticRelSecType(s->type))
527 continue;
529 // Unlike other synthetic sections, mergeable output sections contain
530 // data copied from input sections, and there may be a relocation
531 // pointing to its contents if -r or --emit-reloc is given.
532 if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))
533 continue;
535 isec = s;
536 break;
539 if (!isec)
540 continue;
542 // Set the symbol to be relative to the output section so that its st_value
543 // equals the output section address. Note, there may be a gap between the
544 // start of the output section and isec.
545 ctx.in.symTab->addSymbol(makeDefined(ctx, isec->file, "", STB_LOCAL,
546 /*stOther=*/0, STT_SECTION,
547 /*value=*/0, /*size=*/0, &osec));
551 // Today's loaders have a feature to make segments read-only after
552 // processing dynamic relocations to enhance security. PT_GNU_RELRO
553 // is defined for that.
555 // This function returns true if a section needs to be put into a
556 // PT_GNU_RELRO segment.
557 static bool isRelroSection(Ctx &ctx, const OutputSection *sec) {
558 if (!ctx.arg.zRelro)
559 return false;
560 if (sec->relro)
561 return true;
563 uint64_t flags = sec->flags;
565 // Non-allocatable or non-writable sections don't need RELRO because
566 // they are not writable or not even mapped to memory in the first place.
567 // RELRO is for sections that are essentially read-only but need to
568 // be writable only at process startup to allow dynamic linker to
569 // apply relocations.
570 if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
571 return false;
573 // Once initialized, TLS data segments are used as data templates
574 // for a thread-local storage. For each new thread, runtime
575 // allocates memory for a TLS and copy templates there. No thread
576 // are supposed to use templates directly. Thus, it can be in RELRO.
577 if (flags & SHF_TLS)
578 return true;
580 // .init_array, .preinit_array and .fini_array contain pointers to
581 // functions that are executed on process startup or exit. These
582 // pointers are set by the static linker, and they are not expected
583 // to change at runtime. But if you are an attacker, you could do
584 // interesting things by manipulating pointers in .fini_array, for
585 // example. So they are put into RELRO.
586 uint32_t type = sec->type;
587 if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
588 type == SHT_PREINIT_ARRAY)
589 return true;
591 // .got contains pointers to external symbols. They are resolved by
592 // the dynamic linker when a module is loaded into memory, and after
593 // that they are not expected to change. So, it can be in RELRO.
594 if (ctx.in.got && sec == ctx.in.got->getParent())
595 return true;
597 // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
598 // through r2 register, which is reserved for that purpose. Since r2 is used
599 // for accessing .got as well, .got and .toc need to be close enough in the
600 // virtual address space. Usually, .toc comes just after .got. Since we place
601 // .got into RELRO, .toc needs to be placed into RELRO too.
602 if (sec->name == ".toc")
603 return true;
605 // .got.plt contains pointers to external function symbols. They are
606 // by default resolved lazily, so we usually cannot put it into RELRO.
607 // However, if "-z now" is given, the lazy symbol resolution is
608 // disabled, which enables us to put it into RELRO.
609 if (sec == ctx.in.gotPlt->getParent())
610 return ctx.arg.zNow;
612 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())
613 return true;
615 // .dynamic section contains data for the dynamic linker, and
616 // there's no need to write to it at runtime, so it's better to put
617 // it into RELRO.
618 if (sec->name == ".dynamic")
619 return true;
621 // Sections with some special names are put into RELRO. This is a
622 // bit unfortunate because section names shouldn't be significant in
623 // ELF in spirit. But in reality many linker features depend on
624 // magic section names.
625 StringRef s = sec->name;
627 bool abiAgnostic = s == ".data.rel.ro" || s == ".bss.rel.ro" ||
628 s == ".ctors" || s == ".dtors" || s == ".jcr" ||
629 s == ".eh_frame" || s == ".fini_array" ||
630 s == ".init_array" || s == ".preinit_array";
632 bool abiSpecific =
633 ctx.arg.osabi == ELFOSABI_OPENBSD && s == ".openbsd.randomdata";
635 return abiAgnostic || abiSpecific;
638 // We compute a rank for each section. The rank indicates where the
639 // section should be placed in the file. Instead of using simple
640 // numbers (0,1,2...), we use a series of flags. One for each decision
641 // point when placing the section.
642 // Using flags has two key properties:
643 // * It is easy to check if a give branch was taken.
644 // * It is easy two see how similar two ranks are (see getRankProximity).
645 enum RankFlags {
646 RF_NOT_ADDR_SET = 1 << 27,
647 RF_NOT_ALLOC = 1 << 26,
648 RF_HIP_FATBIN = 1 << 19,
649 RF_PARTITION = 1 << 18, // Partition number (8 bits)
650 RF_LARGE_ALT = 1 << 15,
651 RF_WRITE = 1 << 14,
652 RF_EXEC_WRITE = 1 << 13,
653 RF_EXEC = 1 << 12,
654 RF_RODATA = 1 << 11,
655 RF_LARGE = 1 << 10,
656 RF_NOT_RELRO = 1 << 9,
657 RF_NOT_TLS = 1 << 8,
658 RF_BSS = 1 << 7,
661 unsigned elf::getSectionRank(Ctx &ctx, OutputSection &osec) {
662 unsigned rank = osec.partition * RF_PARTITION;
664 // We want to put section specified by -T option first, so we
665 // can start assigning VA starting from them later.
666 if (ctx.arg.sectionStartMap.count(osec.name))
667 return rank;
668 rank |= RF_NOT_ADDR_SET;
670 // Allocatable sections go first to reduce the total PT_LOAD size and
671 // so debug info doesn't change addresses in actual code.
672 if (!(osec.flags & SHF_ALLOC))
673 return rank | RF_NOT_ALLOC;
675 // Sort sections based on their access permission in the following
676 // order: R, RX, RXW, RW(RELRO), RW(non-RELRO).
678 // Read-only sections come first such that they go in the PT_LOAD covering the
679 // program headers at the start of the file.
681 // The layout for writable sections is PT_LOAD(PT_GNU_RELRO(.data.rel.ro
682 // .bss.rel.ro) | .data .bss), where | marks where page alignment happens.
683 // An alternative ordering is PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro
684 // .bss.rel.ro) | .bss), but it may waste more bytes due to 2 alignment
685 // places.
686 bool isExec = osec.flags & SHF_EXECINSTR;
687 bool isWrite = osec.flags & SHF_WRITE;
689 if (!isWrite && !isExec) {
690 // Among PROGBITS sections, place .lrodata further from .text.
691 // For -z lrodata-after-bss, place .lrodata after .lbss like GNU ld. This
692 // layout has one extra PT_LOAD, but alleviates relocation overflow
693 // pressure for absolute relocations referencing small data from -fno-pic
694 // relocatable files.
695 if (osec.flags & SHF_X86_64_LARGE && ctx.arg.emachine == EM_X86_64)
696 rank |= ctx.arg.zLrodataAfterBss ? RF_LARGE_ALT : 0;
697 else
698 rank |= ctx.arg.zLrodataAfterBss ? 0 : RF_LARGE;
700 if (osec.type == SHT_LLVM_PART_EHDR)
702 else if (osec.type == SHT_LLVM_PART_PHDR)
703 rank |= 1;
704 else if (osec.name == ".interp")
705 rank |= 2;
706 // Put .note sections at the beginning so that they are likely to be
707 // included in a truncate core file. In particular, .note.gnu.build-id, if
708 // available, can identify the object file.
709 else if (osec.type == SHT_NOTE)
710 rank |= 3;
711 // Make PROGBITS sections (e.g .rodata .eh_frame) closer to .text to
712 // alleviate relocation overflow pressure. Large special sections such as
713 // .dynstr and .dynsym can be away from .text.
714 else if (osec.type != SHT_PROGBITS)
715 rank |= 4;
716 else
717 rank |= RF_RODATA;
718 } else if (isExec) {
719 rank |= isWrite ? RF_EXEC_WRITE : RF_EXEC;
720 } else {
721 rank |= RF_WRITE;
722 // The TLS initialization block needs to be a single contiguous block. Place
723 // TLS sections directly before the other RELRO sections.
724 if (!(osec.flags & SHF_TLS))
725 rank |= RF_NOT_TLS;
726 if (isRelroSection(ctx, &osec))
727 osec.relro = true;
728 else
729 rank |= RF_NOT_RELRO;
730 // Place .ldata and .lbss after .bss. Making .bss closer to .text
731 // alleviates relocation overflow pressure.
732 // For -z lrodata-after-bss, place .lbss/.lrodata/.ldata after .bss.
733 // .bss/.lbss being adjacent reuses the NOBITS size optimization.
734 if (osec.flags & SHF_X86_64_LARGE && ctx.arg.emachine == EM_X86_64) {
735 rank |= ctx.arg.zLrodataAfterBss
736 ? (osec.type == SHT_NOBITS ? 1 : RF_LARGE_ALT)
737 : RF_LARGE;
741 // Within TLS sections, or within other RelRo sections, or within non-RelRo
742 // sections, place non-NOBITS sections first.
743 if (osec.type == SHT_NOBITS)
744 rank |= RF_BSS;
746 // Put HIP fatbin related sections further away to avoid wasting relocation
747 // range to jump over them. Make sure .hip_fatbin is the furthest.
748 if (osec.name == ".hipFatBinSegment")
749 rank |= RF_HIP_FATBIN;
750 if (osec.name == ".hip_gpubin_handle")
751 rank |= RF_HIP_FATBIN | 2;
752 if (osec.name == ".hip_fatbin")
753 rank |= RF_HIP_FATBIN | RF_WRITE | 3;
755 // Some architectures have additional ordering restrictions for sections
756 // within the same PT_LOAD.
757 if (ctx.arg.emachine == EM_PPC64) {
758 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
759 // that we would like to make sure appear is a specific order to maximize
760 // their coverage by a single signed 16-bit offset from the TOC base
761 // pointer.
762 StringRef name = osec.name;
763 if (name == ".got")
764 rank |= 1;
765 else if (name == ".toc")
766 rank |= 2;
769 if (ctx.arg.emachine == EM_MIPS) {
770 if (osec.name != ".got")
771 rank |= 1;
772 // All sections with SHF_MIPS_GPREL flag should be grouped together
773 // because data in these sections is addressable with a gp relative address.
774 if (osec.flags & SHF_MIPS_GPREL)
775 rank |= 2;
778 if (ctx.arg.emachine == EM_RISCV) {
779 // .sdata and .sbss are placed closer to make GP relaxation more profitable
780 // and match GNU ld.
781 StringRef name = osec.name;
782 if (name == ".sdata" || (osec.type == SHT_NOBITS && name != ".sbss"))
783 rank |= 1;
786 return rank;
789 static bool compareSections(Ctx &ctx, const SectionCommand *aCmd,
790 const SectionCommand *bCmd) {
791 const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
792 const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
794 if (a->sortRank != b->sortRank)
795 return a->sortRank < b->sortRank;
797 if (!(a->sortRank & RF_NOT_ADDR_SET))
798 return ctx.arg.sectionStartMap.lookup(a->name) <
799 ctx.arg.sectionStartMap.lookup(b->name);
800 return false;
803 void PhdrEntry::add(OutputSection *sec) {
804 lastSec = sec;
805 if (!firstSec)
806 firstSec = sec;
807 p_align = std::max(p_align, sec->addralign);
808 if (p_type == PT_LOAD)
809 sec->ptLoad = this;
812 // A statically linked position-dependent executable should only contain
813 // IRELATIVE relocations and no other dynamic relocations. Encapsulation symbols
814 // __rel[a]_iplt_{start,end} will be defined for .rel[a].dyn, to be
815 // processed by the libc runtime. Other executables or DSOs use dynamic tags
816 // instead.
817 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
818 if (ctx.arg.isPic)
819 return;
821 // __rela_iplt_{start,end} are initially defined relative to dummy section 0.
822 // We'll override ctx.out.elfHeader with relaDyn later when we are sure that
823 // .rela.dyn will be present in the output.
824 std::string name = ctx.arg.isRela ? "__rela_iplt_start" : "__rel_iplt_start";
825 ctx.sym.relaIpltStart =
826 addOptionalRegular(ctx, name, ctx.out.elfHeader.get(), 0, STV_HIDDEN);
827 name.replace(name.size() - 5, 5, "end");
828 ctx.sym.relaIpltEnd =
829 addOptionalRegular(ctx, name, ctx.out.elfHeader.get(), 0, STV_HIDDEN);
832 // This function generates assignments for predefined symbols (e.g. _end or
833 // _etext) and inserts them into the commands sequence to be processed at the
834 // appropriate time. This ensures that the value is going to be correct by the
835 // time any references to these symbols are processed and is equivalent to
836 // defining these symbols explicitly in the linker script.
837 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
838 if (ctx.sym.globalOffsetTable) {
839 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
840 // to the start of the .got or .got.plt section.
841 InputSection *sec = ctx.in.gotPlt.get();
842 if (!ctx.target->gotBaseSymInGotPlt)
843 sec = ctx.in.mipsGot ? cast<InputSection>(ctx.in.mipsGot.get())
844 : cast<InputSection>(ctx.in.got.get());
845 ctx.sym.globalOffsetTable->section = sec;
848 // .rela_iplt_{start,end} mark the start and the end of the section containing
849 // IRELATIVE relocations.
850 if (ctx.sym.relaIpltStart) {
851 auto &dyn = getIRelativeSection(ctx);
852 if (dyn.isNeeded()) {
853 ctx.sym.relaIpltStart->section = &dyn;
854 ctx.sym.relaIpltEnd->section = &dyn;
855 ctx.sym.relaIpltEnd->value = dyn.getSize();
859 PhdrEntry *last = nullptr;
860 OutputSection *lastRO = nullptr;
861 auto isLarge = [&ctx = ctx](OutputSection *osec) {
862 return ctx.arg.emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
864 for (Partition &part : ctx.partitions) {
865 for (auto &p : part.phdrs) {
866 if (p->p_type != PT_LOAD)
867 continue;
868 last = p.get();
869 if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
870 lastRO = p->lastSec;
874 if (lastRO) {
875 // _etext is the first location after the last read-only loadable segment
876 // that does not contain large sections.
877 if (ctx.sym.etext1)
878 ctx.sym.etext1->section = lastRO;
879 if (ctx.sym.etext2)
880 ctx.sym.etext2->section = lastRO;
883 if (last) {
884 // _edata points to the end of the last non-large mapped initialized
885 // section.
886 OutputSection *edata = nullptr;
887 for (OutputSection *os : ctx.outputSections) {
888 if (os->type != SHT_NOBITS && !isLarge(os))
889 edata = os;
890 if (os == last->lastSec)
891 break;
894 if (ctx.sym.edata1)
895 ctx.sym.edata1->section = edata;
896 if (ctx.sym.edata2)
897 ctx.sym.edata2->section = edata;
899 // _end is the first location after the uninitialized data region.
900 if (ctx.sym.end1)
901 ctx.sym.end1->section = last->lastSec;
902 if (ctx.sym.end2)
903 ctx.sym.end2->section = last->lastSec;
906 if (ctx.sym.bss) {
907 // On RISC-V, set __bss_start to the start of .sbss if present.
908 OutputSection *sbss =
909 ctx.arg.emachine == EM_RISCV ? findSection(ctx, ".sbss") : nullptr;
910 ctx.sym.bss->section = sbss ? sbss : findSection(ctx, ".bss");
913 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
914 // be equal to the _gp symbol's value.
915 if (ctx.sym.mipsGp) {
916 // Find GP-relative section with the lowest address
917 // and use this address to calculate default _gp value.
918 for (OutputSection *os : ctx.outputSections) {
919 if (os->flags & SHF_MIPS_GPREL) {
920 ctx.sym.mipsGp->section = os;
921 ctx.sym.mipsGp->value = 0x7ff0;
922 break;
928 // We want to find how similar two ranks are.
929 // The more branches in getSectionRank that match, the more similar they are.
930 // Since each branch corresponds to a bit flag, we can just use
931 // countLeadingZeros.
932 static int getRankProximity(OutputSection *a, SectionCommand *b) {
933 auto *osd = dyn_cast<OutputDesc>(b);
934 return (osd && osd->osec.hasInputSections)
935 ? llvm::countl_zero(a->sortRank ^ osd->osec.sortRank)
936 : -1;
939 // When placing orphan sections, we want to place them after symbol assignments
940 // so that an orphan after
941 // begin_foo = .;
942 // foo : { *(foo) }
943 // end_foo = .;
944 // doesn't break the intended meaning of the begin/end symbols.
945 // We don't want to go over sections since findOrphanPos is the
946 // one in charge of deciding the order of the sections.
947 // We don't want to go over changes to '.', since doing so in
948 // rx_sec : { *(rx_sec) }
949 // . = ALIGN(0x1000);
950 // /* The RW PT_LOAD starts here*/
951 // rw_sec : { *(rw_sec) }
952 // would mean that the RW PT_LOAD would become unaligned.
953 static bool shouldSkip(SectionCommand *cmd) {
954 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
955 return assign->name != ".";
956 return false;
959 // We want to place orphan sections so that they share as much
960 // characteristics with their neighbors as possible. For example, if
961 // both are rw, or both are tls.
962 static SmallVectorImpl<SectionCommand *>::iterator
963 findOrphanPos(Ctx &ctx, SmallVectorImpl<SectionCommand *>::iterator b,
964 SmallVectorImpl<SectionCommand *>::iterator e) {
965 // Place non-alloc orphan sections at the end. This matches how we assign file
966 // offsets to non-alloc sections.
967 OutputSection *sec = &cast<OutputDesc>(*e)->osec;
968 if (!(sec->flags & SHF_ALLOC))
969 return e;
971 // As a special case, place .relro_padding before the SymbolAssignment using
972 // DATA_SEGMENT_RELRO_END, if present.
973 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent()) {
974 auto i = std::find_if(b, e, [=](SectionCommand *a) {
975 if (auto *assign = dyn_cast<SymbolAssignment>(a))
976 return assign->dataSegmentRelroEnd;
977 return false;
979 if (i != e)
980 return i;
983 // Find the most similar output section as the anchor. Rank Proximity is a
984 // value in the range [-1, 32] where [0, 32] indicates potential anchors (0:
985 // least similar; 32: identical). -1 means not an anchor.
987 // In the event of proximity ties, we select the first or last section
988 // depending on whether the orphan's rank is smaller.
989 int maxP = 0;
990 auto i = e;
991 for (auto j = b; j != e; ++j) {
992 int p = getRankProximity(sec, *j);
993 if (p > maxP ||
994 (p == maxP && cast<OutputDesc>(*j)->osec.sortRank <= sec->sortRank)) {
995 maxP = p;
996 i = j;
999 if (i == e)
1000 return e;
1002 auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
1003 auto *osd = dyn_cast<OutputDesc>(cmd);
1004 return osd && osd->osec.hasInputSections;
1007 // Then, scan backward or forward through the script for a suitable insertion
1008 // point. If i's rank is larger, the orphan section can be placed before i.
1010 // However, don't do this if custom program headers are defined. Otherwise,
1011 // adding the orphan to a previous segment can change its flags, for example,
1012 // making a read-only segment writable. If memory regions are defined, an
1013 // orphan section should continue the same region as the found section to
1014 // better resemble the behavior of GNU ld.
1015 bool mustAfter =
1016 ctx.script->hasPhdrsCommands() || !ctx.script->memoryRegions.empty();
1017 if (cast<OutputDesc>(*i)->osec.sortRank <= sec->sortRank || mustAfter) {
1018 for (auto j = ++i; j != e; ++j) {
1019 if (!isOutputSecWithInputSections(*j))
1020 continue;
1021 if (getRankProximity(sec, *j) != maxP)
1022 break;
1023 i = j + 1;
1025 } else {
1026 for (; i != b; --i)
1027 if (isOutputSecWithInputSections(i[-1]))
1028 break;
1031 // As a special case, if the orphan section is the last section, put
1032 // it at the very end, past any other commands.
1033 // This matches bfd's behavior and is convenient when the linker script fully
1034 // specifies the start of the file, but doesn't care about the end (the non
1035 // alloc sections for example).
1036 if (std::find_if(i, e, isOutputSecWithInputSections) == e)
1037 return e;
1039 while (i != e && shouldSkip(*i))
1040 ++i;
1041 return i;
1044 // Adds random priorities to sections not already in the map.
1045 static void maybeShuffle(Ctx &ctx,
1046 DenseMap<const InputSectionBase *, int> &order) {
1047 if (ctx.arg.shuffleSections.empty())
1048 return;
1050 SmallVector<InputSectionBase *, 0> matched, sections = ctx.inputSections;
1051 matched.reserve(sections.size());
1052 for (const auto &patAndSeed : ctx.arg.shuffleSections) {
1053 matched.clear();
1054 for (InputSectionBase *sec : sections)
1055 if (patAndSeed.first.match(sec->name))
1056 matched.push_back(sec);
1057 const uint32_t seed = patAndSeed.second;
1058 if (seed == UINT32_MAX) {
1059 // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1060 // section order is stable even if the number of sections changes. This is
1061 // useful to catch issues like static initialization order fiasco
1062 // reliably.
1063 std::reverse(matched.begin(), matched.end());
1064 } else {
1065 std::mt19937 g(seed ? seed : std::random_device()());
1066 llvm::shuffle(matched.begin(), matched.end(), g);
1068 size_t i = 0;
1069 for (InputSectionBase *&sec : sections)
1070 if (patAndSeed.first.match(sec->name))
1071 sec = matched[i++];
1074 // Existing priorities are < 0, so use priorities >= 0 for the missing
1075 // sections.
1076 int prio = 0;
1077 for (InputSectionBase *sec : sections) {
1078 if (order.try_emplace(sec, prio).second)
1079 ++prio;
1083 // Builds section order for handling --symbol-ordering-file.
1084 static DenseMap<const InputSectionBase *, int> buildSectionOrder(Ctx &ctx) {
1085 DenseMap<const InputSectionBase *, int> sectionOrder;
1086 // Use the rarely used option --call-graph-ordering-file to sort sections.
1087 if (!ctx.arg.callGraphProfile.empty())
1088 return computeCallGraphProfileOrder(ctx);
1090 if (ctx.arg.symbolOrderingFile.empty())
1091 return sectionOrder;
1093 struct SymbolOrderEntry {
1094 int priority;
1095 bool present;
1098 // Build a map from symbols to their priorities. Symbols that didn't
1099 // appear in the symbol ordering file have the lowest priority 0.
1100 // All explicitly mentioned symbols have negative (higher) priorities.
1101 DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
1102 int priority = -ctx.arg.symbolOrderingFile.size();
1103 for (StringRef s : ctx.arg.symbolOrderingFile)
1104 symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
1106 // Build a map from sections to their priorities.
1107 auto addSym = [&](Symbol &sym) {
1108 auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
1109 if (it == symbolOrder.end())
1110 return;
1111 SymbolOrderEntry &ent = it->second;
1112 ent.present = true;
1114 maybeWarnUnorderableSymbol(ctx, &sym);
1116 if (auto *d = dyn_cast<Defined>(&sym)) {
1117 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1118 int &priority = sectionOrder[cast<InputSectionBase>(sec)];
1119 priority = std::min(priority, ent.priority);
1124 // We want both global and local symbols. We get the global ones from the
1125 // symbol table and iterate the object files for the local ones.
1126 for (Symbol *sym : ctx.symtab->getSymbols())
1127 addSym(*sym);
1129 for (ELFFileBase *file : ctx.objectFiles)
1130 for (Symbol *sym : file->getLocalSymbols())
1131 addSym(*sym);
1133 if (ctx.arg.warnSymbolOrdering)
1134 for (auto orderEntry : symbolOrder)
1135 if (!orderEntry.second.present)
1136 Warn(ctx) << "symbol ordering file: no such symbol: "
1137 << orderEntry.first.val();
1139 return sectionOrder;
1142 // Sorts the sections in ISD according to the provided section order.
1143 static void
1144 sortISDBySectionOrder(Ctx &ctx, InputSectionDescription *isd,
1145 const DenseMap<const InputSectionBase *, int> &order,
1146 bool executableOutputSection) {
1147 SmallVector<InputSection *, 0> unorderedSections;
1148 SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
1149 uint64_t unorderedSize = 0;
1150 uint64_t totalSize = 0;
1152 for (InputSection *isec : isd->sections) {
1153 if (executableOutputSection)
1154 totalSize += isec->getSize();
1155 auto i = order.find(isec);
1156 if (i == order.end()) {
1157 unorderedSections.push_back(isec);
1158 unorderedSize += isec->getSize();
1159 continue;
1161 orderedSections.push_back({isec, i->second});
1163 llvm::sort(orderedSections, llvm::less_second());
1165 // Find an insertion point for the ordered section list in the unordered
1166 // section list. On targets with limited-range branches, this is the mid-point
1167 // of the unordered section list. This decreases the likelihood that a range
1168 // extension thunk will be needed to enter or exit the ordered region. If the
1169 // ordered section list is a list of hot functions, we can generally expect
1170 // the ordered functions to be called more often than the unordered functions,
1171 // making it more likely that any particular call will be within range, and
1172 // therefore reducing the number of thunks required.
1174 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1175 // If the layout is:
1177 // 8MB hot
1178 // 32MB cold
1180 // only the first 8-16MB of the cold code (depending on which hot function it
1181 // is actually calling) can call the hot code without a range extension thunk.
1182 // However, if we use this layout:
1184 // 16MB cold
1185 // 8MB hot
1186 // 16MB cold
1188 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1189 // of the second block of cold code can call the hot code without a thunk. So
1190 // we effectively double the amount of code that could potentially call into
1191 // the hot code without a thunk.
1193 // The above is not necessary if total size of input sections in this "isd"
1194 // is small. Note that we assume all input sections are executable if the
1195 // output section is executable (which is not always true but supposed to
1196 // cover most cases).
1197 size_t insPt = 0;
1198 if (executableOutputSection && !orderedSections.empty() &&
1199 ctx.target->getThunkSectionSpacing() &&
1200 totalSize >= ctx.target->getThunkSectionSpacing()) {
1201 uint64_t unorderedPos = 0;
1202 for (; insPt != unorderedSections.size(); ++insPt) {
1203 unorderedPos += unorderedSections[insPt]->getSize();
1204 if (unorderedPos > unorderedSize / 2)
1205 break;
1209 isd->sections.clear();
1210 for (InputSection *isec : ArrayRef(unorderedSections).slice(0, insPt))
1211 isd->sections.push_back(isec);
1212 for (std::pair<InputSection *, int> p : orderedSections)
1213 isd->sections.push_back(p.first);
1214 for (InputSection *isec : ArrayRef(unorderedSections).slice(insPt))
1215 isd->sections.push_back(isec);
1218 static void sortSection(Ctx &ctx, OutputSection &osec,
1219 const DenseMap<const InputSectionBase *, int> &order) {
1220 StringRef name = osec.name;
1222 // Never sort these.
1223 if (name == ".init" || name == ".fini")
1224 return;
1226 // Sort input sections by priority using the list provided by
1227 // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1228 // digit radix sort. The sections may be sorted stably again by a more
1229 // significant key.
1230 if (!order.empty())
1231 for (SectionCommand *b : osec.commands)
1232 if (auto *isd = dyn_cast<InputSectionDescription>(b))
1233 sortISDBySectionOrder(ctx, isd, order, osec.flags & SHF_EXECINSTR);
1235 if (ctx.script->hasSectionsCommand)
1236 return;
1238 if (name == ".init_array" || name == ".fini_array") {
1239 osec.sortInitFini();
1240 } else if (name == ".ctors" || name == ".dtors") {
1241 osec.sortCtorsDtors();
1242 } else if (ctx.arg.emachine == EM_PPC64 && name == ".toc") {
1243 // .toc is allocated just after .got and is accessed using GOT-relative
1244 // relocations. Object files compiled with small code model have an
1245 // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1246 // To reduce the risk of relocation overflow, .toc contents are sorted so
1247 // that sections having smaller relocation offsets are at beginning of .toc
1248 assert(osec.commands.size() == 1);
1249 auto *isd = cast<InputSectionDescription>(osec.commands[0]);
1250 llvm::stable_sort(isd->sections,
1251 [](const InputSection *a, const InputSection *b) -> bool {
1252 return a->file->ppc64SmallCodeModelTocRelocs &&
1253 !b->file->ppc64SmallCodeModelTocRelocs;
1258 // If no layout was provided by linker script, we want to apply default
1259 // sorting for special input sections. This also handles --symbol-ordering-file.
1260 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1261 // Build the order once since it is expensive.
1262 DenseMap<const InputSectionBase *, int> order = buildSectionOrder(ctx);
1263 maybeShuffle(ctx, order);
1264 for (SectionCommand *cmd : ctx.script->sectionCommands)
1265 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1266 sortSection(ctx, osd->osec, order);
1269 template <class ELFT> void Writer<ELFT>::sortSections() {
1270 llvm::TimeTraceScope timeScope("Sort sections");
1272 // Don't sort if using -r. It is not necessary and we want to preserve the
1273 // relative order for SHF_LINK_ORDER sections.
1274 if (ctx.arg.relocatable) {
1275 ctx.script->adjustOutputSections();
1276 return;
1279 sortInputSections();
1281 for (SectionCommand *cmd : ctx.script->sectionCommands)
1282 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1283 osd->osec.sortRank = getSectionRank(ctx, osd->osec);
1284 if (!ctx.script->hasSectionsCommand) {
1285 // OutputDescs are mostly contiguous, but may be interleaved with
1286 // SymbolAssignments in the presence of INSERT commands.
1287 auto mid = std::stable_partition(
1288 ctx.script->sectionCommands.begin(), ctx.script->sectionCommands.end(),
1289 [](SectionCommand *cmd) { return isa<OutputDesc>(cmd); });
1290 std::stable_sort(
1291 ctx.script->sectionCommands.begin(), mid,
1292 [&ctx = ctx](auto *l, auto *r) { return compareSections(ctx, l, r); });
1295 // Process INSERT commands and update output section attributes. From this
1296 // point onwards the order of script->sectionCommands is fixed.
1297 ctx.script->processInsertCommands();
1298 ctx.script->adjustOutputSections();
1300 if (ctx.script->hasSectionsCommand)
1301 sortOrphanSections();
1303 ctx.script->adjustSectionsAfterSorting();
1306 template <class ELFT> void Writer<ELFT>::sortOrphanSections() {
1307 // Orphan sections are sections present in the input files which are
1308 // not explicitly placed into the output file by the linker script.
1310 // The sections in the linker script are already in the correct
1311 // order. We have to figuere out where to insert the orphan
1312 // sections.
1314 // The order of the sections in the script is arbitrary and may not agree with
1315 // compareSections. This means that we cannot easily define a strict weak
1316 // ordering. To see why, consider a comparison of a section in the script and
1317 // one not in the script. We have a two simple options:
1318 // * Make them equivalent (a is not less than b, and b is not less than a).
1319 // The problem is then that equivalence has to be transitive and we can
1320 // have sections a, b and c with only b in a script and a less than c
1321 // which breaks this property.
1322 // * Use compareSectionsNonScript. Given that the script order doesn't have
1323 // to match, we can end up with sections a, b, c, d where b and c are in the
1324 // script and c is compareSectionsNonScript less than b. In which case d
1325 // can be equivalent to c, a to b and d < a. As a concrete example:
1326 // .a (rx) # not in script
1327 // .b (rx) # in script
1328 // .c (ro) # in script
1329 // .d (ro) # not in script
1331 // The way we define an order then is:
1332 // * Sort only the orphan sections. They are in the end right now.
1333 // * Move each orphan section to its preferred position. We try
1334 // to put each section in the last position where it can share
1335 // a PT_LOAD.
1337 // There is some ambiguity as to where exactly a new entry should be
1338 // inserted, because Commands contains not only output section
1339 // commands but also other types of commands such as symbol assignment
1340 // expressions. There's no correct answer here due to the lack of the
1341 // formal specification of the linker script. We use heuristics to
1342 // determine whether a new output command should be added before or
1343 // after another commands. For the details, look at shouldSkip
1344 // function.
1346 auto i = ctx.script->sectionCommands.begin();
1347 auto e = ctx.script->sectionCommands.end();
1348 auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
1349 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1350 return osd->osec.sectionIndex == UINT32_MAX;
1351 return false;
1354 // Sort the orphan sections.
1355 std::stable_sort(nonScriptI, e, [&ctx = ctx](auto *l, auto *r) {
1356 return compareSections(ctx, l, r);
1359 // As a horrible special case, skip the first . assignment if it is before any
1360 // section. We do this because it is common to set a load address by starting
1361 // the script with ". = 0xabcd" and the expectation is that every section is
1362 // after that.
1363 auto firstSectionOrDotAssignment =
1364 std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
1365 if (firstSectionOrDotAssignment != e &&
1366 isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1367 ++firstSectionOrDotAssignment;
1368 i = firstSectionOrDotAssignment;
1370 while (nonScriptI != e) {
1371 auto pos = findOrphanPos(ctx, i, nonScriptI);
1372 OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
1374 // As an optimization, find all sections with the same sort rank
1375 // and insert them with one rotate.
1376 unsigned rank = orphan->sortRank;
1377 auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
1378 return cast<OutputDesc>(cmd)->osec.sortRank != rank;
1380 std::rotate(pos, nonScriptI, end);
1381 nonScriptI = end;
1385 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1386 InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1387 InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1388 // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1389 // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1390 if (!la || !lb)
1391 return la && !lb;
1392 OutputSection *aOut = la->getParent();
1393 OutputSection *bOut = lb->getParent();
1395 if (aOut == bOut)
1396 return la->outSecOff < lb->outSecOff;
1397 if (aOut->addr == bOut->addr)
1398 return aOut->sectionIndex < bOut->sectionIndex;
1399 return aOut->addr < bOut->addr;
1402 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1403 llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1404 for (OutputSection *sec : ctx.outputSections) {
1405 if (!(sec->flags & SHF_LINK_ORDER))
1406 continue;
1408 // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1409 // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1410 if (!ctx.arg.relocatable && ctx.arg.emachine == EM_ARM &&
1411 sec->type == SHT_ARM_EXIDX)
1412 continue;
1414 // Link order may be distributed across several InputSectionDescriptions.
1415 // Sorting is performed separately.
1416 SmallVector<InputSection **, 0> scriptSections;
1417 SmallVector<InputSection *, 0> sections;
1418 for (SectionCommand *cmd : sec->commands) {
1419 auto *isd = dyn_cast<InputSectionDescription>(cmd);
1420 if (!isd)
1421 continue;
1422 bool hasLinkOrder = false;
1423 scriptSections.clear();
1424 sections.clear();
1425 for (InputSection *&isec : isd->sections) {
1426 if (isec->flags & SHF_LINK_ORDER) {
1427 InputSection *link = isec->getLinkOrderDep();
1428 if (link && !link->getParent())
1429 ErrAlways(ctx) << isec << ": sh_link points to discarded section "
1430 << link;
1431 hasLinkOrder = true;
1433 scriptSections.push_back(&isec);
1434 sections.push_back(isec);
1436 if (hasLinkOrder && errCount(ctx) == 0) {
1437 llvm::stable_sort(sections, compareByFilePosition);
1438 for (int i = 0, n = sections.size(); i != n; ++i)
1439 *scriptSections[i] = sections[i];
1445 static void finalizeSynthetic(Ctx &ctx, SyntheticSection *sec) {
1446 if (sec && sec->isNeeded() && sec->getParent()) {
1447 llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1448 sec->finalizeContents();
1452 static bool canInsertPadding(OutputSection *sec) {
1453 StringRef s = sec->name;
1454 return s == ".bss" || s == ".data" || s == ".data.rel.ro" || s == ".lbss" ||
1455 s == ".ldata" || s == ".lrodata" || s == ".ltext" || s == ".rodata" ||
1456 s.starts_with(".text");
1459 static void randomizeSectionPadding(Ctx &ctx) {
1460 std::mt19937 g(*ctx.arg.randomizeSectionPadding);
1461 PhdrEntry *curPtLoad = nullptr;
1462 for (OutputSection *os : ctx.outputSections) {
1463 if (!canInsertPadding(os))
1464 continue;
1465 for (SectionCommand *bc : os->commands) {
1466 if (auto *isd = dyn_cast<InputSectionDescription>(bc)) {
1467 SmallVector<InputSection *, 0> tmp;
1468 if (os->ptLoad != curPtLoad) {
1469 tmp.push_back(make<RandomizePaddingSection>(
1470 ctx, g() % ctx.arg.maxPageSize, os));
1471 curPtLoad = os->ptLoad;
1473 for (InputSection *isec : isd->sections) {
1474 // Probability of inserting padding is 1 in 16.
1475 if (g() % 16 == 0)
1476 tmp.push_back(
1477 make<RandomizePaddingSection>(ctx, isec->addralign, os));
1478 tmp.push_back(isec);
1480 isd->sections = std::move(tmp);
1486 // We need to generate and finalize the content that depends on the address of
1487 // InputSections. As the generation of the content may also alter InputSection
1488 // addresses we must converge to a fixed point. We do that here. See the comment
1489 // in Writer<ELFT>::finalizeSections().
1490 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1491 llvm::TimeTraceScope timeScope("Finalize address dependent content");
1492 AArch64Err843419Patcher a64p(ctx);
1493 ARMErr657417Patcher a32p(ctx);
1494 ctx.script->assignAddresses();
1496 // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1497 // do require the relative addresses of OutputSections because linker scripts
1498 // can assign Virtual Addresses to OutputSections that are not monotonically
1499 // increasing. Anything here must be repeatable, since spilling may change
1500 // section order.
1501 const auto finalizeOrderDependentContent = [this] {
1502 for (Partition &part : ctx.partitions)
1503 finalizeSynthetic(ctx, part.armExidx.get());
1504 resolveShfLinkOrder();
1506 finalizeOrderDependentContent();
1508 // Converts call x@GDPLT to call __tls_get_addr
1509 if (ctx.arg.emachine == EM_HEXAGON)
1510 hexagonTLSSymbolUpdate(ctx);
1512 if (ctx.arg.randomizeSectionPadding)
1513 randomizeSectionPadding(ctx);
1515 uint32_t pass = 0, assignPasses = 0;
1516 for (;;) {
1517 bool changed = ctx.target->needsThunks
1518 ? tc.createThunks(pass, ctx.outputSections)
1519 : ctx.target->relaxOnce(pass);
1520 bool spilled = ctx.script->spillSections();
1521 changed |= spilled;
1522 ++pass;
1524 // With Thunk Size much smaller than branch range we expect to
1525 // converge quickly; if we get to 30 something has gone wrong.
1526 if (changed && pass >= 30) {
1527 Err(ctx) << (ctx.target->needsThunks ? "thunk creation not converged"
1528 : "relaxation not converged");
1529 break;
1532 if (ctx.arg.fixCortexA53Errata843419) {
1533 if (changed)
1534 ctx.script->assignAddresses();
1535 changed |= a64p.createFixes();
1537 if (ctx.arg.fixCortexA8) {
1538 if (changed)
1539 ctx.script->assignAddresses();
1540 changed |= a32p.createFixes();
1543 finalizeSynthetic(ctx, ctx.in.got.get());
1544 if (ctx.in.mipsGot)
1545 ctx.in.mipsGot->updateAllocSize(ctx);
1547 for (Partition &part : ctx.partitions) {
1548 // The R_AARCH64_AUTH_RELATIVE has a smaller addend field as bits [63:32]
1549 // encode the signing schema. We've put relocations in .relr.auth.dyn
1550 // during RelocationScanner::processAux, but the target VA for some of
1551 // them might be wider than 32 bits. We can only know the final VA at this
1552 // point, so move relocations with large values from .relr.auth.dyn to
1553 // .rela.dyn. See also AArch64::relocate.
1554 if (part.relrAuthDyn) {
1555 auto it = llvm::remove_if(
1556 part.relrAuthDyn->relocs, [this, &part](const RelativeReloc &elem) {
1557 const Relocation &reloc = elem.inputSec->relocs()[elem.relocIdx];
1558 if (isInt<32>(reloc.sym->getVA(ctx, reloc.addend)))
1559 return false;
1560 part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, elem.inputSec,
1561 reloc.offset,
1562 DynamicReloc::AddendOnlyWithTargetVA,
1563 *reloc.sym, reloc.addend, R_ABS});
1564 return true;
1566 changed |= (it != part.relrAuthDyn->relocs.end());
1567 part.relrAuthDyn->relocs.erase(it, part.relrAuthDyn->relocs.end());
1569 if (part.relaDyn)
1570 changed |= part.relaDyn->updateAllocSize(ctx);
1571 if (part.relrDyn)
1572 changed |= part.relrDyn->updateAllocSize(ctx);
1573 if (part.relrAuthDyn)
1574 changed |= part.relrAuthDyn->updateAllocSize(ctx);
1575 if (part.memtagGlobalDescriptors)
1576 changed |= part.memtagGlobalDescriptors->updateAllocSize(ctx);
1579 std::pair<const OutputSection *, const Defined *> changes =
1580 ctx.script->assignAddresses();
1581 if (!changed) {
1582 // Some symbols may be dependent on section addresses. When we break the
1583 // loop, the symbol values are finalized because a previous
1584 // assignAddresses() finalized section addresses.
1585 if (!changes.first && !changes.second)
1586 break;
1587 if (++assignPasses == 5) {
1588 if (changes.first)
1589 Err(ctx) << "address (0x" << Twine::utohexstr(changes.first->addr)
1590 << ") of section '" << changes.first->name
1591 << "' does not converge";
1592 if (changes.second)
1593 Err(ctx) << "assignment to symbol " << changes.second
1594 << " does not converge";
1595 break;
1597 } else if (spilled) {
1598 // Spilling can change relative section order.
1599 finalizeOrderDependentContent();
1602 if (!ctx.arg.relocatable)
1603 ctx.target->finalizeRelax(pass);
1605 if (ctx.arg.relocatable)
1606 for (OutputSection *sec : ctx.outputSections)
1607 sec->addr = 0;
1609 // If addrExpr is set, the address may not be a multiple of the alignment.
1610 // Warn because this is error-prone.
1611 for (SectionCommand *cmd : ctx.script->sectionCommands)
1612 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1613 OutputSection *osec = &osd->osec;
1614 if (osec->addr % osec->addralign != 0)
1615 Warn(ctx) << "address (0x" << Twine::utohexstr(osec->addr)
1616 << ") of section " << osec->name
1617 << " is not a multiple of alignment (" << osec->addralign
1618 << ")";
1621 // Sizes are no longer allowed to grow, so all allowable spills have been
1622 // taken. Remove any leftover potential spills.
1623 ctx.script->erasePotentialSpillSections();
1626 // If Input Sections have been shrunk (basic block sections) then
1627 // update symbol values and sizes associated with these sections. With basic
1628 // block sections, input sections can shrink when the jump instructions at
1629 // the end of the section are relaxed.
1630 static void fixSymbolsAfterShrinking(Ctx &ctx) {
1631 for (InputFile *File : ctx.objectFiles) {
1632 parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1633 auto *def = dyn_cast<Defined>(Sym);
1634 if (!def)
1635 return;
1637 const SectionBase *sec = def->section;
1638 if (!sec)
1639 return;
1641 const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1642 if (!inputSec || !inputSec->bytesDropped)
1643 return;
1645 const size_t OldSize = inputSec->content().size();
1646 const size_t NewSize = OldSize - inputSec->bytesDropped;
1648 if (def->value > NewSize && def->value <= OldSize) {
1649 LLVM_DEBUG(llvm::dbgs()
1650 << "Moving symbol " << Sym->getName() << " from "
1651 << def->value << " to "
1652 << def->value - inputSec->bytesDropped << " bytes\n");
1653 def->value -= inputSec->bytesDropped;
1654 return;
1657 if (def->value + def->size > NewSize && def->value <= OldSize &&
1658 def->value + def->size <= OldSize) {
1659 LLVM_DEBUG(llvm::dbgs()
1660 << "Shrinking symbol " << Sym->getName() << " from "
1661 << def->size << " to " << def->size - inputSec->bytesDropped
1662 << " bytes\n");
1663 def->size -= inputSec->bytesDropped;
1669 // If basic block sections exist, there are opportunities to delete fall thru
1670 // jumps and shrink jump instructions after basic block reordering. This
1671 // relaxation pass does that. It is only enabled when --optimize-bb-jumps
1672 // option is used.
1673 template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1674 assert(ctx.arg.optimizeBBJumps);
1675 SmallVector<InputSection *, 0> storage;
1677 ctx.script->assignAddresses();
1678 // For every output section that has executable input sections, this
1679 // does the following:
1680 // 1. Deletes all direct jump instructions in input sections that
1681 // jump to the following section as it is not required.
1682 // 2. If there are two consecutive jump instructions, it checks
1683 // if they can be flipped and one can be deleted.
1684 for (OutputSection *osec : ctx.outputSections) {
1685 if (!(osec->flags & SHF_EXECINSTR))
1686 continue;
1687 ArrayRef<InputSection *> sections = getInputSections(*osec, storage);
1688 size_t numDeleted = 0;
1689 // Delete all fall through jump instructions. Also, check if two
1690 // consecutive jump instructions can be flipped so that a fall
1691 // through jmp instruction can be deleted.
1692 for (size_t i = 0, e = sections.size(); i != e; ++i) {
1693 InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1694 InputSection &sec = *sections[i];
1695 numDeleted += ctx.target->deleteFallThruJmpInsn(sec, sec.file, next);
1697 if (numDeleted > 0) {
1698 ctx.script->assignAddresses();
1699 LLVM_DEBUG(llvm::dbgs()
1700 << "Removing " << numDeleted << " fall through jumps\n");
1704 fixSymbolsAfterShrinking(ctx);
1706 for (OutputSection *osec : ctx.outputSections)
1707 for (InputSection *is : getInputSections(*osec, storage))
1708 is->trim();
1711 // In order to allow users to manipulate linker-synthesized sections,
1712 // we had to add synthetic sections to the input section list early,
1713 // even before we make decisions whether they are needed. This allows
1714 // users to write scripts like this: ".mygot : { .got }".
1716 // Doing it has an unintended side effects. If it turns out that we
1717 // don't need a .got (for example) at all because there's no
1718 // relocation that needs a .got, we don't want to emit .got.
1720 // To deal with the above problem, this function is called after
1721 // scanRelocations is called to remove synthetic sections that turn
1722 // out to be empty.
1723 static void removeUnusedSyntheticSections(Ctx &ctx) {
1724 // All input synthetic sections that can be empty are placed after
1725 // all regular ones. Reverse iterate to find the first synthetic section
1726 // after a non-synthetic one which will be our starting point.
1727 auto start =
1728 llvm::find_if(llvm::reverse(ctx.inputSections), [](InputSectionBase *s) {
1729 return !isa<SyntheticSection>(s);
1730 }).base();
1732 // Remove unused synthetic sections from ctx.inputSections;
1733 DenseSet<InputSectionBase *> unused;
1734 auto end =
1735 std::remove_if(start, ctx.inputSections.end(), [&](InputSectionBase *s) {
1736 auto *sec = cast<SyntheticSection>(s);
1737 if (sec->getParent() && sec->isNeeded())
1738 return false;
1739 // .relr.auth.dyn relocations may be moved to .rela.dyn in
1740 // finalizeAddressDependentContent, making .rela.dyn no longer empty.
1741 // Conservatively keep .rela.dyn. .relr.auth.dyn can be made empty, but
1742 // we would fail to remove it here.
1743 if (ctx.arg.emachine == EM_AARCH64 && ctx.arg.relrPackDynRelocs &&
1744 sec == ctx.mainPart->relaDyn.get())
1745 return false;
1746 unused.insert(sec);
1747 return true;
1749 ctx.inputSections.erase(end, ctx.inputSections.end());
1751 // Remove unused synthetic sections from the corresponding input section
1752 // description and orphanSections.
1753 for (auto *sec : unused)
1754 if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
1755 for (SectionCommand *cmd : osec->commands)
1756 if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
1757 llvm::erase_if(isd->sections, [&](InputSection *isec) {
1758 return unused.count(isec);
1760 llvm::erase_if(ctx.script->orphanSections, [&](const InputSectionBase *sec) {
1761 return unused.count(sec);
1765 // Create output section objects and add them to OutputSections.
1766 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1767 if (!ctx.arg.relocatable) {
1768 ctx.out.preinitArray = findSection(ctx, ".preinit_array");
1769 ctx.out.initArray = findSection(ctx, ".init_array");
1770 ctx.out.finiArray = findSection(ctx, ".fini_array");
1772 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1773 // symbols for sections, so that the runtime can get the start and end
1774 // addresses of each section by section name. Add such symbols.
1775 addStartEndSymbols();
1776 for (SectionCommand *cmd : ctx.script->sectionCommands)
1777 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1778 addStartStopSymbols(osd->osec);
1780 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1781 // It should be okay as no one seems to care about the type.
1782 // Even the author of gold doesn't remember why gold behaves that way.
1783 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1784 if (ctx.mainPart->dynamic->parent) {
1785 Symbol *s = ctx.symtab->addSymbol(Defined{
1786 ctx, ctx.internalFile, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1787 /*value=*/0, /*size=*/0, ctx.mainPart->dynamic.get()});
1788 s->isUsedInRegularObj = true;
1791 // Define __rel[a]_iplt_{start,end} symbols if needed.
1792 addRelIpltSymbols();
1794 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1795 // should only be defined in an executable. If .sdata does not exist, its
1796 // value/section does not matter but it has to be relative, so set its
1797 // st_shndx arbitrarily to 1 (ctx.out.elfHeader).
1798 if (ctx.arg.emachine == EM_RISCV) {
1799 if (!ctx.arg.shared) {
1800 OutputSection *sec = findSection(ctx, ".sdata");
1801 addOptionalRegular(ctx, "__global_pointer$",
1802 sec ? sec : ctx.out.elfHeader.get(), 0x800,
1803 STV_DEFAULT);
1804 // Set riscvGlobalPointer to be used by the optional global pointer
1805 // relaxation.
1806 if (ctx.arg.relaxGP) {
1807 Symbol *s = ctx.symtab->find("__global_pointer$");
1808 if (s && s->isDefined())
1809 ctx.sym.riscvGlobalPointer = cast<Defined>(s);
1814 if (ctx.arg.emachine == EM_386 || ctx.arg.emachine == EM_X86_64) {
1815 // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1816 // way that:
1818 // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1819 // computes 0.
1820 // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address
1821 // in the TLS block).
1823 // 2) is special cased in @tpoff computation. To satisfy 1), we define it
1824 // as an absolute symbol of zero. This is different from GNU linkers which
1825 // define _TLS_MODULE_BASE_ relative to the first TLS section.
1826 Symbol *s = ctx.symtab->find("_TLS_MODULE_BASE_");
1827 if (s && s->isUndefined()) {
1828 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
1829 STV_HIDDEN, STT_TLS, /*value=*/0, 0,
1830 /*section=*/nullptr});
1831 ctx.sym.tlsModuleBase = cast<Defined>(s);
1835 // This responsible for splitting up .eh_frame section into
1836 // pieces. The relocation scan uses those pieces, so this has to be
1837 // earlier.
1839 llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1840 for (Partition &part : ctx.partitions)
1841 finalizeSynthetic(ctx, part.ehFrame.get());
1845 demoteSymbolsAndComputeIsPreemptible(ctx);
1847 if (ctx.arg.copyRelocs && ctx.arg.discard != DiscardPolicy::None)
1848 markUsedLocalSymbols<ELFT>(ctx);
1849 demoteAndCopyLocalSymbols(ctx);
1851 if (ctx.arg.copyRelocs)
1852 addSectionSymbols();
1854 // Change values of linker-script-defined symbols from placeholders (assigned
1855 // by declareSymbols) to actual definitions.
1856 ctx.script->processSymbolAssignments();
1858 if (!ctx.arg.relocatable) {
1859 llvm::TimeTraceScope timeScope("Scan relocations");
1860 // Scan relocations. This must be done after every symbol is declared so
1861 // that we can correctly decide if a dynamic relocation is needed. This is
1862 // called after processSymbolAssignments() because it needs to know whether
1863 // a linker-script-defined symbol is absolute.
1864 scanRelocations<ELFT>(ctx);
1865 reportUndefinedSymbols(ctx);
1866 postScanRelocations(ctx);
1868 if (ctx.in.plt && ctx.in.plt->isNeeded())
1869 ctx.in.plt->addSymbols();
1870 if (ctx.in.iplt && ctx.in.iplt->isNeeded())
1871 ctx.in.iplt->addSymbols();
1873 if (ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1874 auto diag =
1875 ctx.arg.unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError &&
1876 !ctx.arg.noinhibitExec
1877 ? DiagLevel::Err
1878 : DiagLevel::Warn;
1879 // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1880 // entries are seen. These cases would otherwise lead to runtime errors
1881 // reported by the dynamic linker.
1883 // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker
1884 // to catch more cases. That is too much for us. Our approach resembles
1885 // the one used in ld.gold, achieves a good balance to be useful but not
1886 // too smart.
1888 // If a DSO reference is resolved by a SharedSymbol, but the SharedSymbol
1889 // is overridden by a hidden visibility Defined (which is later discarded
1890 // due to GC), don't report the diagnostic. However, this may indicate an
1891 // unintended SharedSymbol.
1892 for (SharedFile *file : ctx.sharedFiles) {
1893 bool allNeededIsKnown =
1894 llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1895 return ctx.symtab->soNames.count(CachedHashStringRef(needed));
1897 if (!allNeededIsKnown)
1898 continue;
1899 for (Symbol *sym : file->requiredSymbols) {
1900 if (sym->dsoDefined)
1901 continue;
1902 if (sym->isUndefined() && !sym->isWeak()) {
1903 ELFSyncStream(ctx, diag)
1904 << "undefined reference: " << sym << "\n>>> referenced by "
1905 << file << " (disallowed by --no-allow-shlib-undefined)";
1906 } else if (sym->isDefined() &&
1907 sym->computeBinding(ctx) == STB_LOCAL) {
1908 ELFSyncStream(ctx, diag)
1909 << "non-exported symbol '" << sym << "' in '" << sym->file
1910 << "' is referenced by DSO '" << file << "'";
1918 llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1919 // Now that we have defined all possible global symbols including linker-
1920 // synthesized ones. Visit all symbols to give the finishing touches.
1921 for (Symbol *sym : ctx.symtab->getSymbols()) {
1922 if (!sym->isUsedInRegularObj || !includeInSymtab(ctx, *sym))
1923 continue;
1924 if (!ctx.arg.relocatable)
1925 sym->binding = sym->computeBinding(ctx);
1926 if (ctx.in.symTab)
1927 ctx.in.symTab->addSymbol(sym);
1929 // computeBinding might localize a linker-synthesized hidden symbol
1930 // (e.g. __global_pointer$) that was considered exported.
1931 if (sym->isExported && !sym->isLocal()) {
1932 ctx.partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1933 if (auto *file = dyn_cast<SharedFile>(sym->file))
1934 if (file->isNeeded && !sym->isUndefined())
1935 addVerneed(ctx, *sym);
1939 // We also need to scan the dynamic relocation tables of the other
1940 // partitions and add any referenced symbols to the partition's dynsym.
1941 for (Partition &part :
1942 MutableArrayRef<Partition>(ctx.partitions).slice(1)) {
1943 DenseSet<Symbol *> syms;
1944 for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1945 syms.insert(e.sym);
1946 for (DynamicReloc &reloc : part.relaDyn->relocs)
1947 if (reloc.sym && reloc.needsDynSymIndex() &&
1948 syms.insert(reloc.sym).second)
1949 part.dynSymTab->addSymbol(reloc.sym);
1953 if (ctx.in.mipsGot)
1954 ctx.in.mipsGot->build();
1956 removeUnusedSyntheticSections(ctx);
1957 ctx.script->diagnoseOrphanHandling();
1958 ctx.script->diagnoseMissingSGSectionAddress();
1960 sortSections();
1962 // Create a list of OutputSections, assign sectionIndex, and populate
1963 // ctx.in.shStrTab. If -z nosectionheader is specified, drop non-ALLOC
1964 // sections.
1965 for (SectionCommand *cmd : ctx.script->sectionCommands)
1966 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1967 OutputSection *osec = &osd->osec;
1968 if (!ctx.in.shStrTab && !(osec->flags & SHF_ALLOC))
1969 continue;
1970 ctx.outputSections.push_back(osec);
1971 osec->sectionIndex = ctx.outputSections.size();
1972 if (ctx.in.shStrTab)
1973 osec->shName = ctx.in.shStrTab->addString(osec->name);
1976 // Prefer command line supplied address over other constraints.
1977 for (OutputSection *sec : ctx.outputSections) {
1978 auto i = ctx.arg.sectionStartMap.find(sec->name);
1979 if (i != ctx.arg.sectionStartMap.end())
1980 sec->addrExpr = [=] { return i->second; };
1983 // With the ctx.outputSections available check for GDPLT relocations
1984 // and add __tls_get_addr symbol if needed.
1985 if (ctx.arg.emachine == EM_HEXAGON &&
1986 hexagonNeedsTLSSymbol(ctx.outputSections)) {
1987 Symbol *sym =
1988 ctx.symtab->addSymbol(Undefined{ctx.internalFile, "__tls_get_addr",
1989 STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
1990 sym->isPreemptible = true;
1991 ctx.partitions[0].dynSymTab->addSymbol(sym);
1994 // This is a bit of a hack. A value of 0 means undef, so we set it
1995 // to 1 to make __ehdr_start defined. The section number is not
1996 // particularly relevant.
1997 ctx.out.elfHeader->sectionIndex = 1;
1998 ctx.out.elfHeader->size = sizeof(typename ELFT::Ehdr);
2000 // Binary and relocatable output does not have PHDRS.
2001 // The headers have to be created before finalize as that can influence the
2002 // image base and the dynamic section on mips includes the image base.
2003 if (!ctx.arg.relocatable && !ctx.arg.oFormatBinary) {
2004 for (Partition &part : ctx.partitions) {
2005 part.phdrs = ctx.script->hasPhdrsCommands() ? ctx.script->createPhdrs()
2006 : createPhdrs(part);
2007 if (ctx.arg.emachine == EM_ARM) {
2008 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2009 addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2011 if (ctx.arg.emachine == EM_MIPS) {
2012 // Add separate segments for MIPS-specific sections.
2013 addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2014 addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2015 addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2017 if (ctx.arg.emachine == EM_RISCV)
2018 addPhdrForSection(part, SHT_RISCV_ATTRIBUTES, PT_RISCV_ATTRIBUTES,
2019 PF_R);
2021 ctx.out.programHeaders->size =
2022 sizeof(Elf_Phdr) * ctx.mainPart->phdrs.size();
2024 // Find the TLS segment. This happens before the section layout loop so that
2025 // Android relocation packing can look up TLS symbol addresses. We only need
2026 // to care about the main partition here because all TLS symbols were moved
2027 // to the main partition (see MarkLive.cpp).
2028 for (auto &p : ctx.mainPart->phdrs)
2029 if (p->p_type == PT_TLS)
2030 ctx.tlsPhdr = p.get();
2033 // Some symbols are defined in term of program headers. Now that we
2034 // have the headers, we can find out which sections they point to.
2035 setReservedSymbolSections();
2037 if (ctx.script->noCrossRefs.size()) {
2038 llvm::TimeTraceScope timeScope("Check NOCROSSREFS");
2039 checkNoCrossRefs<ELFT>(ctx);
2043 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2045 finalizeSynthetic(ctx, ctx.in.bss.get());
2046 finalizeSynthetic(ctx, ctx.in.bssRelRo.get());
2047 finalizeSynthetic(ctx, ctx.in.symTabShndx.get());
2048 finalizeSynthetic(ctx, ctx.in.shStrTab.get());
2049 finalizeSynthetic(ctx, ctx.in.strTab.get());
2050 finalizeSynthetic(ctx, ctx.in.got.get());
2051 finalizeSynthetic(ctx, ctx.in.mipsGot.get());
2052 finalizeSynthetic(ctx, ctx.in.igotPlt.get());
2053 finalizeSynthetic(ctx, ctx.in.gotPlt.get());
2054 finalizeSynthetic(ctx, ctx.in.relaPlt.get());
2055 finalizeSynthetic(ctx, ctx.in.plt.get());
2056 finalizeSynthetic(ctx, ctx.in.iplt.get());
2057 finalizeSynthetic(ctx, ctx.in.ppc32Got2.get());
2058 finalizeSynthetic(ctx, ctx.in.partIndex.get());
2060 // Dynamic section must be the last one in this list and dynamic
2061 // symbol table section (dynSymTab) must be the first one.
2062 for (Partition &part : ctx.partitions) {
2063 if (part.relaDyn) {
2064 part.relaDyn->mergeRels();
2065 // Compute DT_RELACOUNT to be used by part.dynamic.
2066 part.relaDyn->partitionRels();
2067 finalizeSynthetic(ctx, part.relaDyn.get());
2069 if (part.relrDyn) {
2070 part.relrDyn->mergeRels();
2071 finalizeSynthetic(ctx, part.relrDyn.get());
2073 if (part.relrAuthDyn) {
2074 part.relrAuthDyn->mergeRels();
2075 finalizeSynthetic(ctx, part.relrAuthDyn.get());
2078 finalizeSynthetic(ctx, part.dynSymTab.get());
2079 finalizeSynthetic(ctx, part.gnuHashTab.get());
2080 finalizeSynthetic(ctx, part.hashTab.get());
2081 finalizeSynthetic(ctx, part.verDef.get());
2082 finalizeSynthetic(ctx, part.ehFrameHdr.get());
2083 finalizeSynthetic(ctx, part.verSym.get());
2084 finalizeSynthetic(ctx, part.verNeed.get());
2085 finalizeSynthetic(ctx, part.dynamic.get());
2089 if (!ctx.script->hasSectionsCommand && !ctx.arg.relocatable)
2090 fixSectionAlignments();
2092 // This is used to:
2093 // 1) Create "thunks":
2094 // Jump instructions in many ISAs have small displacements, and therefore
2095 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2096 // JAL instruction can target only +-1 MiB from PC. It is a linker's
2097 // responsibility to create and insert small pieces of code between
2098 // sections to extend the ranges if jump targets are out of range. Such
2099 // code pieces are called "thunks".
2101 // We add thunks at this stage. We couldn't do this before this point
2102 // because this is the earliest point where we know sizes of sections and
2103 // their layouts (that are needed to determine if jump targets are in
2104 // range).
2106 // 2) Update the sections. We need to generate content that depends on the
2107 // address of InputSections. For example, MIPS GOT section content or
2108 // android packed relocations sections content.
2110 // 3) Assign the final values for the linker script symbols. Linker scripts
2111 // sometimes using forward symbol declarations. We want to set the correct
2112 // values. They also might change after adding the thunks.
2113 finalizeAddressDependentContent();
2115 // All information needed for OutputSection part of Map file is available.
2116 if (errCount(ctx))
2117 return;
2120 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2121 // finalizeAddressDependentContent may have added local symbols to the
2122 // static symbol table.
2123 finalizeSynthetic(ctx, ctx.in.symTab.get());
2124 finalizeSynthetic(ctx, ctx.in.debugNames.get());
2125 finalizeSynthetic(ctx, ctx.in.ppc64LongBranchTarget.get());
2126 finalizeSynthetic(ctx, ctx.in.armCmseSGSection.get());
2129 // Relaxation to delete inter-basic block jumps created by basic block
2130 // sections. Run after ctx.in.symTab is finalized as optimizeBasicBlockJumps
2131 // can relax jump instructions based on symbol offset.
2132 if (ctx.arg.optimizeBBJumps)
2133 optimizeBasicBlockJumps();
2135 // Fill other section headers. The dynamic table is finalized
2136 // at the end because some tags like RELSZ depend on result
2137 // of finalizing other sections.
2138 for (OutputSection *sec : ctx.outputSections)
2139 sec->finalize(ctx);
2141 ctx.script->checkFinalScriptConditions();
2143 if (ctx.arg.emachine == EM_ARM && !ctx.arg.isLE && ctx.arg.armBe8) {
2144 addArmInputSectionMappingSymbols(ctx);
2145 sortArmMappingSymbols(ctx);
2149 // Ensure data sections are not mixed with executable sections when
2150 // --execute-only is used. --execute-only make pages executable but not
2151 // readable.
2152 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2153 if (!ctx.arg.executeOnly)
2154 return;
2156 SmallVector<InputSection *, 0> storage;
2157 for (OutputSection *osec : ctx.outputSections)
2158 if (osec->flags & SHF_EXECINSTR)
2159 for (InputSection *isec : getInputSections(*osec, storage))
2160 if (!(isec->flags & SHF_EXECINSTR))
2161 ErrAlways(ctx) << "cannot place " << isec << " into " << osec->name
2162 << ": --execute-only does not support intermingling "
2163 "data and code";
2166 // The linker is expected to define SECNAME_start and SECNAME_end
2167 // symbols for a few sections. This function defines them.
2168 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2169 // If the associated output section does not exist, there is ambiguity as to
2170 // how we define _start and _end symbols for an init/fini section. Users
2171 // expect no "undefined symbol" linker errors and loaders expect equal
2172 // st_value but do not particularly care whether the symbols are defined or
2173 // not. We retain the output section so that the section indexes will be
2174 // correct.
2175 auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2176 if (os) {
2177 Defined *startSym = addOptionalRegular(ctx, start, os, 0);
2178 Defined *stopSym = addOptionalRegular(ctx, end, os, -1);
2179 if (startSym || stopSym)
2180 os->usedInExpression = true;
2181 } else {
2182 addOptionalRegular(ctx, start, ctx.out.elfHeader.get(), 0);
2183 addOptionalRegular(ctx, end, ctx.out.elfHeader.get(), 0);
2187 define("__preinit_array_start", "__preinit_array_end", ctx.out.preinitArray);
2188 define("__init_array_start", "__init_array_end", ctx.out.initArray);
2189 define("__fini_array_start", "__fini_array_end", ctx.out.finiArray);
2191 // As a special case, don't unnecessarily retain .ARM.exidx, which would
2192 // create an empty PT_ARM_EXIDX.
2193 if (OutputSection *sec = findSection(ctx, ".ARM.exidx"))
2194 define("__exidx_start", "__exidx_end", sec);
2197 // If a section name is valid as a C identifier (which is rare because of
2198 // the leading '.'), linkers are expected to define __start_<secname> and
2199 // __stop_<secname> symbols. They are at beginning and end of the section,
2200 // respectively. This is not requested by the ELF standard, but GNU ld and
2201 // gold provide the feature, and used by many programs.
2202 template <class ELFT>
2203 void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
2204 StringRef s = osec.name;
2205 if (!isValidCIdentifier(s))
2206 return;
2207 StringSaver &ss = ctx.saver;
2208 Defined *startSym = addOptionalRegular(ctx, ss.save("__start_" + s), &osec, 0,
2209 ctx.arg.zStartStopVisibility);
2210 Defined *stopSym = addOptionalRegular(ctx, ss.save("__stop_" + s), &osec, -1,
2211 ctx.arg.zStartStopVisibility);
2212 if (startSym || stopSym)
2213 osec.usedInExpression = true;
2216 static bool needsPtLoad(OutputSection *sec) {
2217 if (!(sec->flags & SHF_ALLOC))
2218 return false;
2220 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2221 // responsible for allocating space for them, not the PT_LOAD that
2222 // contains the TLS initialization image.
2223 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2224 return false;
2225 return true;
2228 // Adjust phdr flags according to certain options.
2229 static uint64_t computeFlags(Ctx &ctx, uint64_t flags) {
2230 if (ctx.arg.omagic)
2231 return PF_R | PF_W | PF_X;
2232 if (ctx.arg.executeOnly && (flags & PF_X))
2233 return flags & ~PF_R;
2234 return flags;
2237 // Decide which program headers to create and which sections to include in each
2238 // one.
2239 template <class ELFT>
2240 SmallVector<std::unique_ptr<PhdrEntry>, 0>
2241 Writer<ELFT>::createPhdrs(Partition &part) {
2242 SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;
2243 auto addHdr = [&, &ctx = ctx](unsigned type, unsigned flags) -> PhdrEntry * {
2244 ret.push_back(std::make_unique<PhdrEntry>(ctx, type, flags));
2245 return ret.back().get();
2248 unsigned partNo = part.getNumber(ctx);
2249 bool isMain = partNo == 1;
2251 // Add the first PT_LOAD segment for regular output sections.
2252 uint64_t flags = computeFlags(ctx, PF_R);
2253 PhdrEntry *load = nullptr;
2255 // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2256 // PT_LOAD.
2257 if (!ctx.arg.nmagic && !ctx.arg.omagic) {
2258 // The first phdr entry is PT_PHDR which describes the program header
2259 // itself.
2260 if (isMain)
2261 addHdr(PT_PHDR, PF_R)->add(ctx.out.programHeaders.get());
2262 else
2263 addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2265 // PT_INTERP must be the second entry if exists.
2266 if (OutputSection *cmd = findSection(ctx, ".interp", partNo))
2267 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2269 // Add the headers. We will remove them if they don't fit.
2270 // In the other partitions the headers are ordinary sections, so they don't
2271 // need to be added here.
2272 if (isMain) {
2273 load = addHdr(PT_LOAD, flags);
2274 load->add(ctx.out.elfHeader.get());
2275 load->add(ctx.out.programHeaders.get());
2279 // PT_GNU_RELRO includes all sections that should be marked as
2280 // read-only by dynamic linker after processing relocations.
2281 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2282 // an error message if more than one PT_GNU_RELRO PHDR is required.
2283 auto relRo = std::make_unique<PhdrEntry>(ctx, PT_GNU_RELRO, PF_R);
2284 bool inRelroPhdr = false;
2285 OutputSection *relroEnd = nullptr;
2286 for (OutputSection *sec : ctx.outputSections) {
2287 if (sec->partition != partNo || !needsPtLoad(sec))
2288 continue;
2289 if (isRelroSection(ctx, sec)) {
2290 inRelroPhdr = true;
2291 if (!relroEnd)
2292 relRo->add(sec);
2293 else
2294 ErrAlways(ctx) << "section: " << sec->name
2295 << " is not contiguous with other relro" << " sections";
2296 } else if (inRelroPhdr) {
2297 inRelroPhdr = false;
2298 relroEnd = sec;
2301 relRo->p_align = 1;
2303 for (OutputSection *sec : ctx.outputSections) {
2304 if (!needsPtLoad(sec))
2305 continue;
2307 // Normally, sections in partitions other than the current partition are
2308 // ignored. But partition number 255 is a special case: it contains the
2309 // partition end marker (.part.end). It needs to be added to the main
2310 // partition so that a segment is created for it in the main partition,
2311 // which will cause the dynamic loader to reserve space for the other
2312 // partitions.
2313 if (sec->partition != partNo) {
2314 if (isMain && sec->partition == 255)
2315 addHdr(PT_LOAD, computeFlags(ctx, sec->getPhdrFlags()))->add(sec);
2316 continue;
2319 // Segments are contiguous memory regions that has the same attributes
2320 // (e.g. executable or writable). There is one phdr for each segment.
2321 // Therefore, we need to create a new phdr when the next section has
2322 // incompatible flags or is loaded at a discontiguous address or memory
2323 // region using AT or AT> linker script command, respectively.
2325 // As an exception, we don't create a separate load segment for the ELF
2326 // headers, even if the first "real" output has an AT or AT> attribute.
2328 // In addition, NOBITS sections should only be placed at the end of a LOAD
2329 // segment (since it's represented as p_filesz < p_memsz). If we have a
2330 // not-NOBITS section after a NOBITS, we create a new LOAD for the latter
2331 // even if flags match, so as not to require actually writing the
2332 // supposed-to-be-NOBITS section to the output file. (However, we cannot do
2333 // so when hasSectionsCommand, since we cannot introduce the extra alignment
2334 // needed to create a new LOAD)
2335 uint64_t newFlags = computeFlags(ctx, sec->getPhdrFlags());
2336 // When --no-rosegment is specified, RO and RX sections are compatible.
2337 uint32_t incompatible = flags ^ newFlags;
2338 if (ctx.arg.singleRoRx && !(newFlags & PF_W))
2339 incompatible &= ~PF_X;
2340 if (incompatible)
2341 load = nullptr;
2343 bool sameLMARegion =
2344 load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2345 if (load && sec != relroEnd &&
2346 sec->memRegion == load->firstSec->memRegion &&
2347 (sameLMARegion || load->lastSec == ctx.out.programHeaders.get()) &&
2348 (ctx.script->hasSectionsCommand || sec->type == SHT_NOBITS ||
2349 load->lastSec->type != SHT_NOBITS)) {
2350 load->p_flags |= newFlags;
2351 } else {
2352 load = addHdr(PT_LOAD, newFlags);
2353 flags = newFlags;
2356 load->add(sec);
2359 // Add a TLS segment if any.
2360 auto tlsHdr = std::make_unique<PhdrEntry>(ctx, PT_TLS, PF_R);
2361 for (OutputSection *sec : ctx.outputSections)
2362 if (sec->partition == partNo && sec->flags & SHF_TLS)
2363 tlsHdr->add(sec);
2364 if (tlsHdr->firstSec)
2365 ret.push_back(std::move(tlsHdr));
2367 // Add an entry for .dynamic.
2368 if (OutputSection *sec = part.dynamic->getParent())
2369 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2371 if (relRo->firstSec)
2372 ret.push_back(std::move(relRo));
2374 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2375 if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2376 part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2377 addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2378 ->add(part.ehFrameHdr->getParent());
2380 if (ctx.arg.osabi == ELFOSABI_OPENBSD) {
2381 // PT_OPENBSD_MUTABLE makes the dynamic linker fill the segment with
2382 // zero data, like bss, but it can be treated differently.
2383 if (OutputSection *cmd = findSection(ctx, ".openbsd.mutable", partNo))
2384 addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
2386 // PT_OPENBSD_RANDOMIZE makes the dynamic linker fill the segment
2387 // with random data.
2388 if (OutputSection *cmd = findSection(ctx, ".openbsd.randomdata", partNo))
2389 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2391 // PT_OPENBSD_SYSCALLS makes the kernel and dynamic linker register
2392 // system call sites.
2393 if (OutputSection *cmd = findSection(ctx, ".openbsd.syscalls", partNo))
2394 addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
2397 if (ctx.arg.zGnustack != GnuStackKind::None) {
2398 // PT_GNU_STACK is a special section to tell the loader to make the
2399 // pages for the stack non-executable. If you really want an executable
2400 // stack, you can pass -z execstack, but that's not recommended for
2401 // security reasons.
2402 unsigned perm = PF_R | PF_W;
2403 if (ctx.arg.zGnustack == GnuStackKind::Exec)
2404 perm |= PF_X;
2405 addHdr(PT_GNU_STACK, perm)->p_memsz = ctx.arg.zStackSize;
2408 // PT_OPENBSD_NOBTCFI is an OpenBSD-specific header to mark that the
2409 // executable is expected to violate branch-target CFI checks.
2410 if (ctx.arg.zNoBtCfi)
2411 addHdr(PT_OPENBSD_NOBTCFI, PF_X);
2413 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2414 // is expected to perform W^X violations, such as calling mprotect(2) or
2415 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2416 // OpenBSD.
2417 if (ctx.arg.zWxneeded)
2418 addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2420 if (OutputSection *cmd = findSection(ctx, ".note.gnu.property", partNo))
2421 addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2423 // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2424 // same alignment.
2425 PhdrEntry *note = nullptr;
2426 for (OutputSection *sec : ctx.outputSections) {
2427 if (sec->partition != partNo)
2428 continue;
2429 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2430 if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2431 note = addHdr(PT_NOTE, PF_R);
2432 note->add(sec);
2433 } else {
2434 note = nullptr;
2437 return ret;
2440 template <class ELFT>
2441 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2442 unsigned pType, unsigned pFlags) {
2443 unsigned partNo = part.getNumber(ctx);
2444 auto i = llvm::find_if(ctx.outputSections, [=](OutputSection *cmd) {
2445 return cmd->partition == partNo && cmd->type == shType;
2447 if (i == ctx.outputSections.end())
2448 return;
2450 auto entry = std::make_unique<PhdrEntry>(ctx, pType, pFlags);
2451 entry->add(*i);
2452 part.phdrs.push_back(std::move(entry));
2455 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2456 // This is achieved by assigning an alignment expression to addrExpr of each
2457 // such section.
2458 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2459 const PhdrEntry *prev;
2460 auto pageAlign = [&, &ctx = this->ctx](const PhdrEntry *p) {
2461 OutputSection *cmd = p->firstSec;
2462 if (!cmd)
2463 return;
2464 cmd->alignExpr = [align = cmd->addralign]() { return align; };
2465 if (!cmd->addrExpr) {
2466 // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2467 // padding in the file contents.
2469 // When -z separate-code is used we must not have any overlap in pages
2470 // between an executable segment and a non-executable segment. We align to
2471 // the next maximum page size boundary on transitions between executable
2472 // and non-executable segments.
2474 // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2475 // sections will be extracted to a separate file. Align to the next
2476 // maximum page size boundary so that we can find the ELF header at the
2477 // start. We cannot benefit from overlapping p_offset ranges with the
2478 // previous segment anyway.
2479 if (ctx.arg.zSeparate == SeparateSegmentKind::Loadable ||
2480 (ctx.arg.zSeparate == SeparateSegmentKind::Code && prev &&
2481 (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2482 cmd->type == SHT_LLVM_PART_EHDR)
2483 cmd->addrExpr = [&ctx = this->ctx] {
2484 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize);
2486 // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2487 // it must be the RW. Align to p_align(PT_TLS) to make sure
2488 // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2489 // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2490 // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2491 // be congruent to 0 modulo p_align(PT_TLS).
2493 // Technically this is not required, but as of 2019, some dynamic loaders
2494 // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2495 // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2496 // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2497 // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2498 // blocks correctly. We need to keep the workaround for a while.
2499 else if (ctx.tlsPhdr && ctx.tlsPhdr->firstSec == p->firstSec)
2500 cmd->addrExpr = [&ctx] {
2501 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2502 alignToPowerOf2(ctx.script->getDot() % ctx.arg.maxPageSize,
2503 ctx.tlsPhdr->p_align);
2505 else
2506 cmd->addrExpr = [&ctx] {
2507 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2508 ctx.script->getDot() % ctx.arg.maxPageSize;
2513 for (Partition &part : ctx.partitions) {
2514 prev = nullptr;
2515 for (auto &p : part.phdrs)
2516 if (p->p_type == PT_LOAD && p->firstSec) {
2517 pageAlign(p.get());
2518 prev = p.get();
2523 // Compute an in-file position for a given section. The file offset must be the
2524 // same with its virtual address modulo the page size, so that the loader can
2525 // load executables without any address adjustment.
2526 static uint64_t computeFileOffset(Ctx &ctx, OutputSection *os, uint64_t off) {
2527 // The first section in a PT_LOAD has to have congruent offset and address
2528 // modulo the maximum page size.
2529 if (os->ptLoad && os->ptLoad->firstSec == os)
2530 return alignTo(off, os->ptLoad->p_align, os->addr);
2532 // File offsets are not significant for .bss sections other than the first one
2533 // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2534 // increasing rather than setting to zero.
2535 if (os->type == SHT_NOBITS && (!ctx.tlsPhdr || ctx.tlsPhdr->firstSec != os))
2536 return off;
2538 // If the section is not in a PT_LOAD, we just have to align it.
2539 if (!os->ptLoad)
2540 return alignToPowerOf2(off, os->addralign);
2542 // If two sections share the same PT_LOAD the file offset is calculated
2543 // using this formula: Off2 = Off1 + (VA2 - VA1).
2544 OutputSection *first = os->ptLoad->firstSec;
2545 return first->offset + os->addr - first->addr;
2548 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2549 // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2550 auto needsOffset = [](OutputSection &sec) {
2551 return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2553 uint64_t minAddr = UINT64_MAX;
2554 for (OutputSection *sec : ctx.outputSections)
2555 if (needsOffset(*sec)) {
2556 sec->offset = sec->getLMA();
2557 minAddr = std::min(minAddr, sec->offset);
2560 // Sections are laid out at LMA minus minAddr.
2561 fileSize = 0;
2562 for (OutputSection *sec : ctx.outputSections)
2563 if (needsOffset(*sec)) {
2564 sec->offset -= minAddr;
2565 fileSize = std::max(fileSize, sec->offset + sec->size);
2569 static std::string rangeToString(uint64_t addr, uint64_t len) {
2570 return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2573 // Assign file offsets to output sections.
2574 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2575 ctx.out.programHeaders->offset = ctx.out.elfHeader->size;
2576 uint64_t off = ctx.out.elfHeader->size + ctx.out.programHeaders->size;
2578 PhdrEntry *lastRX = nullptr;
2579 for (Partition &part : ctx.partitions)
2580 for (auto &p : part.phdrs)
2581 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2582 lastRX = p.get();
2584 // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2585 // will not occupy file offsets contained by a PT_LOAD.
2586 for (OutputSection *sec : ctx.outputSections) {
2587 if (!(sec->flags & SHF_ALLOC))
2588 continue;
2589 off = computeFileOffset(ctx, sec, off);
2590 sec->offset = off;
2591 if (sec->type != SHT_NOBITS)
2592 off += sec->size;
2594 // If this is a last section of the last executable segment and that
2595 // segment is the last loadable segment, align the offset of the
2596 // following section to avoid loading non-segments parts of the file.
2597 if (ctx.arg.zSeparate != SeparateSegmentKind::None && lastRX &&
2598 lastRX->lastSec == sec)
2599 off = alignToPowerOf2(off, ctx.arg.maxPageSize);
2601 for (OutputSection *osec : ctx.outputSections) {
2602 if (osec->flags & SHF_ALLOC)
2603 continue;
2604 osec->offset = alignToPowerOf2(off, osec->addralign);
2605 off = osec->offset + osec->size;
2608 sectionHeaderOff = alignToPowerOf2(off, ctx.arg.wordsize);
2609 fileSize =
2610 sectionHeaderOff + (ctx.outputSections.size() + 1) * sizeof(Elf_Shdr);
2612 // Our logic assumes that sections have rising VA within the same segment.
2613 // With use of linker scripts it is possible to violate this rule and get file
2614 // offset overlaps or overflows. That should never happen with a valid script
2615 // which does not move the location counter backwards and usually scripts do
2616 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2617 // kernel, which control segment distribution explicitly and move the counter
2618 // backwards, so we have to allow doing that to support linking them. We
2619 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2620 // we want to prevent file size overflows because it would crash the linker.
2621 for (OutputSection *sec : ctx.outputSections) {
2622 if (sec->type == SHT_NOBITS)
2623 continue;
2624 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2625 ErrAlways(ctx) << "unable to place section " << sec->name
2626 << " at file offset "
2627 << rangeToString(sec->offset, sec->size)
2628 << "; check your linker script for overflows";
2632 // Finalize the program headers. We call this function after we assign
2633 // file offsets and VAs to all sections.
2634 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2635 for (std::unique_ptr<PhdrEntry> &p : part.phdrs) {
2636 OutputSection *first = p->firstSec;
2637 OutputSection *last = p->lastSec;
2639 // .ARM.exidx sections may not be within a single .ARM.exidx
2640 // output section. We always want to describe just the
2641 // SyntheticSection.
2642 if (part.armExidx && p->p_type == PT_ARM_EXIDX) {
2643 p->p_filesz = part.armExidx->getSize();
2644 p->p_memsz = p->p_filesz;
2645 p->p_offset = first->offset + part.armExidx->outSecOff;
2646 p->p_vaddr = first->addr + part.armExidx->outSecOff;
2647 p->p_align = part.armExidx->addralign;
2648 if (part.elfHeader)
2649 p->p_offset -= part.elfHeader->getParent()->offset;
2651 if (!p->hasLMA)
2652 p->p_paddr = first->getLMA() + part.armExidx->outSecOff;
2653 return;
2656 if (first) {
2657 p->p_filesz = last->offset - first->offset;
2658 if (last->type != SHT_NOBITS)
2659 p->p_filesz += last->size;
2661 p->p_memsz = last->addr + last->size - first->addr;
2662 p->p_offset = first->offset;
2663 p->p_vaddr = first->addr;
2665 // File offsets in partitions other than the main partition are relative
2666 // to the offset of the ELF headers. Perform that adjustment now.
2667 if (part.elfHeader)
2668 p->p_offset -= part.elfHeader->getParent()->offset;
2670 if (!p->hasLMA)
2671 p->p_paddr = first->getLMA();
2676 // A helper struct for checkSectionOverlap.
2677 namespace {
2678 struct SectionOffset {
2679 OutputSection *sec;
2680 uint64_t offset;
2682 } // namespace
2684 // Check whether sections overlap for a specific address range (file offsets,
2685 // load and virtual addresses).
2686 static void checkOverlap(Ctx &ctx, StringRef name,
2687 std::vector<SectionOffset> &sections,
2688 bool isVirtualAddr) {
2689 llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2690 return a.offset < b.offset;
2693 // Finding overlap is easy given a vector is sorted by start position.
2694 // If an element starts before the end of the previous element, they overlap.
2695 for (size_t i = 1, end = sections.size(); i < end; ++i) {
2696 SectionOffset a = sections[i - 1];
2697 SectionOffset b = sections[i];
2698 if (b.offset >= a.offset + a.sec->size)
2699 continue;
2701 // If both sections are in OVERLAY we allow the overlapping of virtual
2702 // addresses, because it is what OVERLAY was designed for.
2703 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2704 continue;
2706 Err(ctx) << "section " << a.sec->name << " " << name
2707 << " range overlaps with " << b.sec->name << "\n>>> "
2708 << a.sec->name << " range is "
2709 << rangeToString(a.offset, a.sec->size) << "\n>>> " << b.sec->name
2710 << " range is " << rangeToString(b.offset, b.sec->size);
2714 // Check for overlapping sections and address overflows.
2716 // In this function we check that none of the output sections have overlapping
2717 // file offsets. For SHF_ALLOC sections we also check that the load address
2718 // ranges and the virtual address ranges don't overlap
2719 template <class ELFT> void Writer<ELFT>::checkSections() {
2720 // First, check that section's VAs fit in available address space for target.
2721 for (OutputSection *os : ctx.outputSections)
2722 if ((os->addr + os->size < os->addr) ||
2723 (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2724 Err(ctx) << "section " << os->name << " at 0x"
2725 << utohexstr(os->addr, true) << " of size 0x"
2726 << utohexstr(os->size, true)
2727 << " exceeds available address space";
2729 // Check for overlapping file offsets. In this case we need to skip any
2730 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2731 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2732 // binary is specified only add SHF_ALLOC sections are added to the output
2733 // file so we skip any non-allocated sections in that case.
2734 std::vector<SectionOffset> fileOffs;
2735 for (OutputSection *sec : ctx.outputSections)
2736 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2737 (!ctx.arg.oFormatBinary || (sec->flags & SHF_ALLOC)))
2738 fileOffs.push_back({sec, sec->offset});
2739 checkOverlap(ctx, "file", fileOffs, false);
2741 // When linking with -r there is no need to check for overlapping virtual/load
2742 // addresses since those addresses will only be assigned when the final
2743 // executable/shared object is created.
2744 if (ctx.arg.relocatable)
2745 return;
2747 // Checking for overlapping virtual and load addresses only needs to take
2748 // into account SHF_ALLOC sections since others will not be loaded.
2749 // Furthermore, we also need to skip SHF_TLS sections since these will be
2750 // mapped to other addresses at runtime and can therefore have overlapping
2751 // ranges in the file.
2752 std::vector<SectionOffset> vmas;
2753 for (OutputSection *sec : ctx.outputSections)
2754 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2755 vmas.push_back({sec, sec->addr});
2756 checkOverlap(ctx, "virtual address", vmas, true);
2758 // Finally, check that the load addresses don't overlap. This will usually be
2759 // the same as the virtual addresses but can be different when using a linker
2760 // script with AT().
2761 std::vector<SectionOffset> lmas;
2762 for (OutputSection *sec : ctx.outputSections)
2763 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2764 lmas.push_back({sec, sec->getLMA()});
2765 checkOverlap(ctx, "load address", lmas, false);
2768 // The entry point address is chosen in the following ways.
2770 // 1. the '-e' entry command-line option;
2771 // 2. the ENTRY(symbol) command in a linker control script;
2772 // 3. the value of the symbol _start, if present;
2773 // 4. the number represented by the entry symbol, if it is a number;
2774 // 5. the address 0.
2775 static uint64_t getEntryAddr(Ctx &ctx) {
2776 // Case 1, 2 or 3
2777 if (Symbol *b = ctx.symtab->find(ctx.arg.entry))
2778 return b->getVA(ctx);
2780 // Case 4
2781 uint64_t addr;
2782 if (to_integer(ctx.arg.entry, addr))
2783 return addr;
2785 // Case 5
2786 if (ctx.arg.warnMissingEntry)
2787 Warn(ctx) << "cannot find entry symbol " << ctx.arg.entry
2788 << "; not setting start address";
2789 return 0;
2792 static uint16_t getELFType(Ctx &ctx) {
2793 if (ctx.arg.isPic)
2794 return ET_DYN;
2795 if (ctx.arg.relocatable)
2796 return ET_REL;
2797 return ET_EXEC;
2800 template <class ELFT> void Writer<ELFT>::writeHeader() {
2801 writeEhdr<ELFT>(ctx, ctx.bufferStart, *ctx.mainPart);
2802 writePhdrs<ELFT>(ctx.bufferStart + sizeof(Elf_Ehdr), *ctx.mainPart);
2804 auto *eHdr = reinterpret_cast<Elf_Ehdr *>(ctx.bufferStart);
2805 eHdr->e_type = getELFType(ctx);
2806 eHdr->e_entry = getEntryAddr(ctx);
2808 // If -z nosectionheader is specified, omit the section header table.
2809 if (!ctx.in.shStrTab)
2810 return;
2811 eHdr->e_shoff = sectionHeaderOff;
2813 // Write the section header table.
2815 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2816 // and e_shstrndx fields. When the value of one of these fields exceeds
2817 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2818 // use fields in the section header at index 0 to store
2819 // the value. The sentinel values and fields are:
2820 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2821 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2822 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(ctx.bufferStart + eHdr->e_shoff);
2823 size_t num = ctx.outputSections.size() + 1;
2824 if (num >= SHN_LORESERVE)
2825 sHdrs->sh_size = num;
2826 else
2827 eHdr->e_shnum = num;
2829 uint32_t strTabIndex = ctx.in.shStrTab->getParent()->sectionIndex;
2830 if (strTabIndex >= SHN_LORESERVE) {
2831 sHdrs->sh_link = strTabIndex;
2832 eHdr->e_shstrndx = SHN_XINDEX;
2833 } else {
2834 eHdr->e_shstrndx = strTabIndex;
2837 for (OutputSection *sec : ctx.outputSections)
2838 sec->writeHeaderTo<ELFT>(++sHdrs);
2841 // Open a result file.
2842 template <class ELFT> void Writer<ELFT>::openFile() {
2843 uint64_t maxSize = ctx.arg.is64 ? INT64_MAX : UINT32_MAX;
2844 if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2845 std::string msg;
2846 raw_string_ostream s(msg);
2847 s << "output file too large: " << fileSize << " bytes\n"
2848 << "section sizes:\n";
2849 for (OutputSection *os : ctx.outputSections)
2850 s << os->name << ' ' << os->size << "\n";
2851 ErrAlways(ctx) << msg;
2852 return;
2855 unlinkAsync(ctx.arg.outputFile);
2856 unsigned flags = 0;
2857 if (!ctx.arg.relocatable)
2858 flags |= FileOutputBuffer::F_executable;
2859 if (!ctx.arg.mmapOutputFile)
2860 flags |= FileOutputBuffer::F_no_mmap;
2861 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2862 FileOutputBuffer::create(ctx.arg.outputFile, fileSize, flags);
2864 if (!bufferOrErr) {
2865 ErrAlways(ctx) << "failed to open " << ctx.arg.outputFile << ": "
2866 << bufferOrErr.takeError();
2867 return;
2869 buffer = std::move(*bufferOrErr);
2870 ctx.bufferStart = buffer->getBufferStart();
2873 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2874 parallel::TaskGroup tg;
2875 for (OutputSection *sec : ctx.outputSections)
2876 if (sec->flags & SHF_ALLOC)
2877 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2880 static void fillTrap(std::array<uint8_t, 4> trapInstr, uint8_t *i,
2881 uint8_t *end) {
2882 for (; i + 4 <= end; i += 4)
2883 memcpy(i, trapInstr.data(), 4);
2886 // Fill the last page of executable segments with trap instructions
2887 // instead of leaving them as zero. Even though it is not required by any
2888 // standard, it is in general a good thing to do for security reasons.
2890 // We'll leave other pages in segments as-is because the rest will be
2891 // overwritten by output sections.
2892 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2893 for (Partition &part : ctx.partitions) {
2894 // Fill the last page.
2895 for (std::unique_ptr<PhdrEntry> &p : part.phdrs)
2896 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2897 fillTrap(
2898 ctx.target->trapInstr,
2899 ctx.bufferStart + alignDown(p->firstSec->offset + p->p_filesz, 4),
2900 ctx.bufferStart + alignToPowerOf2(p->firstSec->offset + p->p_filesz,
2901 ctx.arg.maxPageSize));
2903 // Round up the file size of the last segment to the page boundary iff it is
2904 // an executable segment to ensure that other tools don't accidentally
2905 // trim the instruction padding (e.g. when stripping the file).
2906 PhdrEntry *last = nullptr;
2907 for (std::unique_ptr<PhdrEntry> &p : part.phdrs)
2908 if (p->p_type == PT_LOAD)
2909 last = p.get();
2911 if (last && (last->p_flags & PF_X))
2912 last->p_memsz = last->p_filesz =
2913 alignToPowerOf2(last->p_filesz, ctx.arg.maxPageSize);
2917 // Write section contents to a mmap'ed file.
2918 template <class ELFT> void Writer<ELFT>::writeSections() {
2919 llvm::TimeTraceScope timeScope("Write sections");
2922 // In -r or --emit-relocs mode, write the relocation sections first as in
2923 // ELf_Rel targets we might find out that we need to modify the relocated
2924 // section while doing it.
2925 parallel::TaskGroup tg;
2926 for (OutputSection *sec : ctx.outputSections)
2927 if (isStaticRelSecType(sec->type))
2928 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2931 parallel::TaskGroup tg;
2932 for (OutputSection *sec : ctx.outputSections)
2933 if (!isStaticRelSecType(sec->type))
2934 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2937 // Finally, check that all dynamic relocation addends were written correctly.
2938 if (ctx.arg.checkDynamicRelocs && ctx.arg.writeAddends) {
2939 for (OutputSection *sec : ctx.outputSections)
2940 if (isStaticRelSecType(sec->type))
2941 sec->checkDynRelAddends(ctx);
2945 // Computes a hash value of Data using a given hash function.
2946 // In order to utilize multiple cores, we first split data into 1MB
2947 // chunks, compute a hash for each chunk, and then compute a hash value
2948 // of the hash values.
2949 static void
2950 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2951 llvm::ArrayRef<uint8_t> data,
2952 std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2953 std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2954 const size_t hashesSize = chunks.size() * hashBuf.size();
2955 std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2957 // Compute hash values.
2958 parallelFor(0, chunks.size(), [&](size_t i) {
2959 hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2962 // Write to the final output buffer.
2963 hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
2966 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2967 if (!ctx.mainPart->buildId || !ctx.mainPart->buildId->getParent())
2968 return;
2970 if (ctx.arg.buildId == BuildIdKind::Hexstring) {
2971 for (Partition &part : ctx.partitions)
2972 part.buildId->writeBuildId(ctx.arg.buildIdVector);
2973 return;
2976 // Compute a hash of all sections of the output file.
2977 size_t hashSize = ctx.mainPart->buildId->hashSize;
2978 std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2979 MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2980 llvm::ArrayRef<uint8_t> input{ctx.bufferStart, size_t(fileSize)};
2982 // Fedora introduced build ID as "approximation of true uniqueness across all
2983 // binaries that might be used by overlapping sets of people". It does not
2984 // need some security goals that some hash algorithms strive to provide, e.g.
2985 // (second-)preimage and collision resistance. In practice people use 'md5'
2986 // and 'sha1' just for different lengths. Implement them with the more
2987 // efficient BLAKE3.
2988 switch (ctx.arg.buildId) {
2989 case BuildIdKind::Fast:
2990 computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2991 write64le(dest, xxh3_64bits(arr));
2993 break;
2994 case BuildIdKind::Md5:
2995 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2996 memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
2998 break;
2999 case BuildIdKind::Sha1:
3000 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3001 memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
3003 break;
3004 case BuildIdKind::Uuid:
3005 if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
3006 ErrAlways(ctx) << "entropy source failure: " << ec.message();
3007 break;
3008 default:
3009 llvm_unreachable("unknown BuildIdKind");
3011 for (Partition &part : ctx.partitions)
3012 part.buildId->writeBuildId(output);
3015 template void elf::writeResult<ELF32LE>(Ctx &);
3016 template void elf::writeResult<ELF32BE>(Ctx &);
3017 template void elf::writeResult<ELF64LE>(Ctx &);
3018 template void elf::writeResult<ELF64BE>(Ctx &);