[ELF] Refine isExported/isPreemptible condition
[llvm-project.git] / lld / ELF / Writer.cpp
blob487fb119a966b12f1125e89edb366b39bcc3c16d
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 ctx.synthesizedSymbols.push_back(s);
153 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
154 stOther, STT_NOTYPE, val,
155 /*size=*/0, sec});
156 s->isUsedInRegularObj = true;
157 return cast<Defined>(s);
160 // The linker is expected to define some symbols depending on
161 // the linking result. This function defines such symbols.
162 void elf::addReservedSymbols(Ctx &ctx) {
163 if (ctx.arg.emachine == EM_MIPS) {
164 auto addAbsolute = [&](StringRef name) {
165 Symbol *sym =
166 ctx.symtab->addSymbol(Defined{ctx, ctx.internalFile, name, STB_GLOBAL,
167 STV_HIDDEN, STT_NOTYPE, 0, 0, nullptr});
168 sym->isUsedInRegularObj = true;
169 return cast<Defined>(sym);
171 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
172 // so that it points to an absolute address which by default is relative
173 // to GOT. Default offset is 0x7ff0.
174 // See "Global Data Symbols" in Chapter 6 in the following document:
175 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
176 ctx.sym.mipsGp = addAbsolute("_gp");
178 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
179 // start of function and 'gp' pointer into GOT.
180 if (ctx.symtab->find("_gp_disp"))
181 ctx.sym.mipsGpDisp = addAbsolute("_gp_disp");
183 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
184 // pointer. This symbol is used in the code generated by .cpload pseudo-op
185 // in case of using -mno-shared option.
186 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
187 if (ctx.symtab->find("__gnu_local_gp"))
188 ctx.sym.mipsLocalGp = addAbsolute("__gnu_local_gp");
189 } else if (ctx.arg.emachine == EM_PPC) {
190 // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
191 // support Small Data Area, define it arbitrarily as 0.
192 addOptionalRegular(ctx, "_SDA_BASE_", nullptr, 0, STV_HIDDEN);
193 } else if (ctx.arg.emachine == EM_PPC64) {
194 addPPC64SaveRestore(ctx);
197 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
198 // combines the typical ELF GOT with the small data sections. It commonly
199 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
200 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
201 // represent the TOC base which is offset by 0x8000 bytes from the start of
202 // the .got section.
203 // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
204 // correctness of some relocations depends on its value.
205 StringRef gotSymName =
206 (ctx.arg.emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
208 if (Symbol *s = ctx.symtab->find(gotSymName)) {
209 if (s->isDefined()) {
210 ErrAlways(ctx) << s->file << " cannot redefine linker defined symbol '"
211 << gotSymName << "'";
212 return;
215 uint64_t gotOff = 0;
216 if (ctx.arg.emachine == EM_PPC64)
217 gotOff = 0x8000;
219 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
220 STV_HIDDEN, STT_NOTYPE, gotOff, /*size=*/0,
221 ctx.out.elfHeader.get()});
222 ctx.sym.globalOffsetTable = cast<Defined>(s);
225 // __ehdr_start is the location of ELF file headers. Note that we define
226 // this symbol unconditionally even when using a linker script, which
227 // differs from the behavior implemented by GNU linker which only define
228 // this symbol if ELF headers are in the memory mapped segment.
229 addOptionalRegular(ctx, "__ehdr_start", ctx.out.elfHeader.get(), 0,
230 STV_HIDDEN);
232 // __executable_start is not documented, but the expectation of at
233 // least the Android libc is that it points to the ELF header.
234 addOptionalRegular(ctx, "__executable_start", ctx.out.elfHeader.get(), 0,
235 STV_HIDDEN);
237 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
238 // each DSO. The address of the symbol doesn't matter as long as they are
239 // different in different DSOs, so we chose the start address of the DSO.
240 addOptionalRegular(ctx, "__dso_handle", ctx.out.elfHeader.get(), 0,
241 STV_HIDDEN);
243 // If linker script do layout we do not need to create any standard symbols.
244 if (ctx.script->hasSectionsCommand)
245 return;
247 auto add = [&](StringRef s, int64_t pos) {
248 return addOptionalRegular(ctx, s, ctx.out.elfHeader.get(), pos,
249 STV_DEFAULT);
252 ctx.sym.bss = add("__bss_start", 0);
253 ctx.sym.end1 = add("end", -1);
254 ctx.sym.end2 = add("_end", -1);
255 ctx.sym.etext1 = add("etext", -1);
256 ctx.sym.etext2 = add("_etext", -1);
257 ctx.sym.edata1 = add("edata", -1);
258 ctx.sym.edata2 = add("_edata", -1);
261 static void demoteDefined(Defined &sym, DenseMap<SectionBase *, size_t> &map) {
262 if (map.empty())
263 for (auto [i, sec] : llvm::enumerate(sym.file->getSections()))
264 map.try_emplace(sec, i);
265 // Change WEAK to GLOBAL so that if a scanned relocation references sym,
266 // maybeReportUndefined will report an error.
267 uint8_t binding = sym.isWeak() ? uint8_t(STB_GLOBAL) : sym.binding;
268 Undefined(sym.file, sym.getName(), binding, sym.stOther, sym.type,
269 /*discardedSecIdx=*/map.lookup(sym.section))
270 .overwrite(sym);
271 // Eliminate from the symbol table, otherwise we would leave an undefined
272 // symbol if the symbol is unreferenced in the absence of GC.
273 sym.isUsedInRegularObj = false;
276 // If all references to a DSO happen to be weak, the DSO is not added to
277 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid
278 // dangling references to an unneeded DSO. Use a weak binding to avoid
279 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
281 // In addition, demote symbols defined in discarded sections, so that
282 // references to /DISCARD/ discarded symbols will lead to errors.
283 static void demoteSymbolsAndComputeIsPreemptible(Ctx &ctx) {
284 llvm::TimeTraceScope timeScope("Demote symbols");
285 DenseMap<InputFile *, DenseMap<SectionBase *, size_t>> sectionIndexMap;
286 bool hasDynsym = ctx.hasDynsym;
287 bool maybePreemptible = ctx.sharedFiles.size() || ctx.arg.shared;
288 for (Symbol *sym : ctx.symtab->getSymbols()) {
289 if (auto *d = dyn_cast<Defined>(sym)) {
290 if (d->section && !d->section->isLive())
291 demoteDefined(*d, sectionIndexMap[d->file]);
292 } else {
293 auto *s = dyn_cast<SharedSymbol>(sym);
294 if (sym->isLazy() || (s && !cast<SharedFile>(s->file)->isNeeded)) {
295 uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
296 Undefined(ctx.internalFile, sym->getName(), binding, sym->stOther,
297 sym->type)
298 .overwrite(*sym);
299 sym->versionId = VER_NDX_GLOBAL;
303 if (hasDynsym)
304 sym->isPreemptible = maybePreemptible &&
305 (sym->isUndefined() || sym->isExported) &&
306 computeIsPreemptible(ctx, *sym);
310 static OutputSection *findSection(Ctx &ctx, StringRef name,
311 unsigned partition = 1) {
312 for (SectionCommand *cmd : ctx.script->sectionCommands)
313 if (auto *osd = dyn_cast<OutputDesc>(cmd))
314 if (osd->osec.name == name && osd->osec.partition == partition)
315 return &osd->osec;
316 return nullptr;
319 // The main function of the writer.
320 template <class ELFT> void Writer<ELFT>::run() {
321 // Now that we have a complete set of output sections. This function
322 // completes section contents. For example, we need to add strings
323 // to the string table, and add entries to .got and .plt.
324 // finalizeSections does that.
325 finalizeSections();
326 checkExecuteOnly();
328 // If --compressed-debug-sections is specified, compress .debug_* sections.
329 // Do it right now because it changes the size of output sections.
330 for (OutputSection *sec : ctx.outputSections)
331 sec->maybeCompress<ELFT>(ctx);
333 if (ctx.script->hasSectionsCommand)
334 ctx.script->allocateHeaders(ctx.mainPart->phdrs);
336 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
337 // 0 sized region. This has to be done late since only after assignAddresses
338 // we know the size of the sections.
339 for (Partition &part : ctx.partitions)
340 removeEmptyPTLoad(ctx, part.phdrs);
342 if (!ctx.arg.oFormatBinary)
343 assignFileOffsets();
344 else
345 assignFileOffsetsBinary();
347 for (Partition &part : ctx.partitions)
348 setPhdrs(part);
350 // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
351 // because the files may be useful in case checkSections() or openFile()
352 // fails, for example, due to an erroneous file size.
353 writeMapAndCref(ctx);
355 // Handle --print-memory-usage option.
356 if (ctx.arg.printMemoryUsage)
357 ctx.script->printMemoryUsage(ctx.e.outs());
359 if (ctx.arg.checkSections)
360 checkSections();
362 // It does not make sense try to open the file if we have error already.
363 if (errCount(ctx))
364 return;
367 llvm::TimeTraceScope timeScope("Write output file");
368 // Write the result down to a file.
369 openFile();
370 if (errCount(ctx))
371 return;
373 if (!ctx.arg.oFormatBinary) {
374 if (ctx.arg.zSeparate != SeparateSegmentKind::None)
375 writeTrapInstr();
376 writeHeader();
377 writeSections();
378 } else {
379 writeSectionsBinary();
382 // Backfill .note.gnu.build-id section content. This is done at last
383 // because the content is usually a hash value of the entire output file.
384 writeBuildId();
385 if (errCount(ctx))
386 return;
388 if (!ctx.e.disableOutput) {
389 if (auto e = buffer->commit())
390 Err(ctx) << "failed to write output '" << buffer->getPath()
391 << "': " << std::move(e);
394 if (!ctx.arg.cmseOutputLib.empty())
395 writeARMCmseImportLib<ELFT>(ctx);
399 template <class ELFT, class RelTy>
400 static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
401 llvm::ArrayRef<RelTy> rels) {
402 for (const RelTy &rel : rels) {
403 Symbol &sym = file->getRelocTargetSym(rel);
404 if (sym.isLocal())
405 sym.used = true;
409 // The function ensures that the "used" field of local symbols reflects the fact
410 // that the symbol is used in a relocation from a live section.
411 template <class ELFT> static void markUsedLocalSymbols(Ctx &ctx) {
412 // With --gc-sections, the field is already filled.
413 // See MarkLive<ELFT>::resolveReloc().
414 if (ctx.arg.gcSections)
415 return;
416 for (ELFFileBase *file : ctx.objectFiles) {
417 ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
418 for (InputSectionBase *s : f->getSections()) {
419 InputSection *isec = dyn_cast_or_null<InputSection>(s);
420 if (!isec)
421 continue;
422 if (isec->type == SHT_REL) {
423 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
424 } else if (isec->type == SHT_RELA) {
425 markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
426 } else if (isec->type == SHT_CREL) {
427 // The is64=true variant also works with ELF32 since only the r_symidx
428 // member is used.
429 for (Elf_Crel_Impl<true> r : RelocsCrel<true>(isec->content_)) {
430 Symbol &sym = file->getSymbol(r.r_symidx);
431 if (sym.isLocal())
432 sym.used = true;
439 static bool shouldKeepInSymtab(Ctx &ctx, const Defined &sym) {
440 if (sym.isSection())
441 return false;
443 // If --emit-reloc or -r is given, preserve symbols referenced by relocations
444 // from live sections.
445 if (sym.used && ctx.arg.copyRelocs)
446 return true;
448 // Exclude local symbols pointing to .ARM.exidx sections.
449 // They are probably mapping symbols "$d", which are optional for these
450 // sections. After merging the .ARM.exidx sections, some of these symbols
451 // may become dangling. The easiest way to avoid the issue is not to add
452 // them to the symbol table from the beginning.
453 if (ctx.arg.emachine == EM_ARM && sym.section &&
454 sym.section->type == SHT_ARM_EXIDX)
455 return false;
457 if (ctx.arg.discard == DiscardPolicy::None)
458 return true;
459 if (ctx.arg.discard == DiscardPolicy::All)
460 return false;
462 // In ELF assembly .L symbols are normally discarded by the assembler.
463 // If the assembler fails to do so, the linker discards them if
464 // * --discard-locals is used.
465 // * The symbol is in a SHF_MERGE section, which is normally the reason for
466 // the assembler keeping the .L symbol.
467 if (sym.getName().starts_with(".L") &&
468 (ctx.arg.discard == DiscardPolicy::Locals ||
469 (sym.section && (sym.section->flags & SHF_MERGE))))
470 return false;
471 return true;
474 bool elf::includeInSymtab(Ctx &ctx, const Symbol &b) {
475 if (auto *d = dyn_cast<Defined>(&b)) {
476 // Always include absolute symbols.
477 SectionBase *sec = d->section;
478 if (!sec)
479 return true;
480 assert(sec->isLive());
482 if (auto *s = dyn_cast<MergeInputSection>(sec))
483 return s->getSectionPiece(d->value).live;
484 return true;
486 return b.used || !ctx.arg.gcSections;
489 // Scan local symbols to:
491 // - demote symbols defined relative to /DISCARD/ discarded input sections so
492 // that relocations referencing them will lead to errors.
493 // - copy eligible symbols to .symTab
494 static void demoteAndCopyLocalSymbols(Ctx &ctx) {
495 llvm::TimeTraceScope timeScope("Add local symbols");
496 for (ELFFileBase *file : ctx.objectFiles) {
497 DenseMap<SectionBase *, size_t> sectionIndexMap;
498 for (Symbol *b : file->getLocalSymbols()) {
499 assert(b->isLocal() && "should have been caught in initializeSymbols()");
500 auto *dr = dyn_cast<Defined>(b);
501 if (!dr)
502 continue;
504 if (dr->section && !dr->section->isLive())
505 demoteDefined(*dr, sectionIndexMap);
506 else if (ctx.in.symTab && includeInSymtab(ctx, *b) &&
507 shouldKeepInSymtab(ctx, *dr))
508 ctx.in.symTab->addSymbol(b);
513 // Create a section symbol for each output section so that we can represent
514 // relocations that point to the section. If we know that no relocation is
515 // referring to a section (that happens if the section is a synthetic one), we
516 // don't create a section symbol for that section.
517 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
518 for (SectionCommand *cmd : ctx.script->sectionCommands) {
519 auto *osd = dyn_cast<OutputDesc>(cmd);
520 if (!osd)
521 continue;
522 OutputSection &osec = osd->osec;
523 InputSectionBase *isec = nullptr;
524 // Iterate over all input sections and add a STT_SECTION symbol if any input
525 // section may be a relocation target.
526 for (SectionCommand *cmd : osec.commands) {
527 auto *isd = dyn_cast<InputSectionDescription>(cmd);
528 if (!isd)
529 continue;
530 for (InputSectionBase *s : isd->sections) {
531 // Relocations are not using REL[A] section symbols.
532 if (isStaticRelSecType(s->type))
533 continue;
535 // Unlike other synthetic sections, mergeable output sections contain
536 // data copied from input sections, and there may be a relocation
537 // pointing to its contents if -r or --emit-reloc is given.
538 if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))
539 continue;
541 isec = s;
542 break;
545 if (!isec)
546 continue;
548 // Set the symbol to be relative to the output section so that its st_value
549 // equals the output section address. Note, there may be a gap between the
550 // start of the output section and isec.
551 ctx.in.symTab->addSymbol(makeDefined(ctx, isec->file, "", STB_LOCAL,
552 /*stOther=*/0, STT_SECTION,
553 /*value=*/0, /*size=*/0, &osec));
557 // Today's loaders have a feature to make segments read-only after
558 // processing dynamic relocations to enhance security. PT_GNU_RELRO
559 // is defined for that.
561 // This function returns true if a section needs to be put into a
562 // PT_GNU_RELRO segment.
563 static bool isRelroSection(Ctx &ctx, const OutputSection *sec) {
564 if (!ctx.arg.zRelro)
565 return false;
566 if (sec->relro)
567 return true;
569 uint64_t flags = sec->flags;
571 // Non-allocatable or non-writable sections don't need RELRO because
572 // they are not writable or not even mapped to memory in the first place.
573 // RELRO is for sections that are essentially read-only but need to
574 // be writable only at process startup to allow dynamic linker to
575 // apply relocations.
576 if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
577 return false;
579 // Once initialized, TLS data segments are used as data templates
580 // for a thread-local storage. For each new thread, runtime
581 // allocates memory for a TLS and copy templates there. No thread
582 // are supposed to use templates directly. Thus, it can be in RELRO.
583 if (flags & SHF_TLS)
584 return true;
586 // .init_array, .preinit_array and .fini_array contain pointers to
587 // functions that are executed on process startup or exit. These
588 // pointers are set by the static linker, and they are not expected
589 // to change at runtime. But if you are an attacker, you could do
590 // interesting things by manipulating pointers in .fini_array, for
591 // example. So they are put into RELRO.
592 uint32_t type = sec->type;
593 if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
594 type == SHT_PREINIT_ARRAY)
595 return true;
597 // .got contains pointers to external symbols. They are resolved by
598 // the dynamic linker when a module is loaded into memory, and after
599 // that they are not expected to change. So, it can be in RELRO.
600 if (ctx.in.got && sec == ctx.in.got->getParent())
601 return true;
603 // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
604 // through r2 register, which is reserved for that purpose. Since r2 is used
605 // for accessing .got as well, .got and .toc need to be close enough in the
606 // virtual address space. Usually, .toc comes just after .got. Since we place
607 // .got into RELRO, .toc needs to be placed into RELRO too.
608 if (sec->name == ".toc")
609 return true;
611 // .got.plt contains pointers to external function symbols. They are
612 // by default resolved lazily, so we usually cannot put it into RELRO.
613 // However, if "-z now" is given, the lazy symbol resolution is
614 // disabled, which enables us to put it into RELRO.
615 if (sec == ctx.in.gotPlt->getParent())
616 return ctx.arg.zNow;
618 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())
619 return true;
621 // .dynamic section contains data for the dynamic linker, and
622 // there's no need to write to it at runtime, so it's better to put
623 // it into RELRO.
624 if (sec->name == ".dynamic")
625 return true;
627 // Sections with some special names are put into RELRO. This is a
628 // bit unfortunate because section names shouldn't be significant in
629 // ELF in spirit. But in reality many linker features depend on
630 // magic section names.
631 StringRef s = sec->name;
633 bool abiAgnostic = s == ".data.rel.ro" || s == ".bss.rel.ro" ||
634 s == ".ctors" || s == ".dtors" || s == ".jcr" ||
635 s == ".eh_frame" || s == ".fini_array" ||
636 s == ".init_array" || s == ".preinit_array";
638 bool abiSpecific =
639 ctx.arg.osabi == ELFOSABI_OPENBSD && s == ".openbsd.randomdata";
641 return abiAgnostic || abiSpecific;
644 // We compute a rank for each section. The rank indicates where the
645 // section should be placed in the file. Instead of using simple
646 // numbers (0,1,2...), we use a series of flags. One for each decision
647 // point when placing the section.
648 // Using flags has two key properties:
649 // * It is easy to check if a give branch was taken.
650 // * It is easy two see how similar two ranks are (see getRankProximity).
651 enum RankFlags {
652 RF_NOT_ADDR_SET = 1 << 27,
653 RF_NOT_ALLOC = 1 << 26,
654 RF_PARTITION = 1 << 18, // Partition number (8 bits)
655 RF_LARGE_ALT = 1 << 15,
656 RF_WRITE = 1 << 14,
657 RF_EXEC_WRITE = 1 << 13,
658 RF_EXEC = 1 << 12,
659 RF_RODATA = 1 << 11,
660 RF_LARGE = 1 << 10,
661 RF_NOT_RELRO = 1 << 9,
662 RF_NOT_TLS = 1 << 8,
663 RF_BSS = 1 << 7,
666 unsigned elf::getSectionRank(Ctx &ctx, OutputSection &osec) {
667 unsigned rank = osec.partition * RF_PARTITION;
669 // We want to put section specified by -T option first, so we
670 // can start assigning VA starting from them later.
671 if (ctx.arg.sectionStartMap.count(osec.name))
672 return rank;
673 rank |= RF_NOT_ADDR_SET;
675 // Allocatable sections go first to reduce the total PT_LOAD size and
676 // so debug info doesn't change addresses in actual code.
677 if (!(osec.flags & SHF_ALLOC))
678 return rank | RF_NOT_ALLOC;
680 // Sort sections based on their access permission in the following
681 // order: R, RX, RXW, RW(RELRO), RW(non-RELRO).
683 // Read-only sections come first such that they go in the PT_LOAD covering the
684 // program headers at the start of the file.
686 // The layout for writable sections is PT_LOAD(PT_GNU_RELRO(.data.rel.ro
687 // .bss.rel.ro) | .data .bss), where | marks where page alignment happens.
688 // An alternative ordering is PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro
689 // .bss.rel.ro) | .bss), but it may waste more bytes due to 2 alignment
690 // places.
691 bool isExec = osec.flags & SHF_EXECINSTR;
692 bool isWrite = osec.flags & SHF_WRITE;
694 if (!isWrite && !isExec) {
695 // Among PROGBITS sections, place .lrodata further from .text.
696 // For -z lrodata-after-bss, place .lrodata after .lbss like GNU ld. This
697 // layout has one extra PT_LOAD, but alleviates relocation overflow
698 // pressure for absolute relocations referencing small data from -fno-pic
699 // relocatable files.
700 if (osec.flags & SHF_X86_64_LARGE && ctx.arg.emachine == EM_X86_64)
701 rank |= ctx.arg.zLrodataAfterBss ? RF_LARGE_ALT : 0;
702 else
703 rank |= ctx.arg.zLrodataAfterBss ? 0 : RF_LARGE;
705 if (osec.type == SHT_LLVM_PART_EHDR)
707 else if (osec.type == SHT_LLVM_PART_PHDR)
708 rank |= 1;
709 else if (osec.name == ".interp")
710 rank |= 2;
711 // Put .note sections at the beginning so that they are likely to be
712 // included in a truncate core file. In particular, .note.gnu.build-id, if
713 // available, can identify the object file.
714 else if (osec.type == SHT_NOTE)
715 rank |= 3;
716 // Make PROGBITS sections (e.g .rodata .eh_frame) closer to .text to
717 // alleviate relocation overflow pressure. Large special sections such as
718 // .dynstr and .dynsym can be away from .text.
719 else if (osec.type != SHT_PROGBITS)
720 rank |= 4;
721 else
722 rank |= RF_RODATA;
723 } else if (isExec) {
724 rank |= isWrite ? RF_EXEC_WRITE : RF_EXEC;
725 } else {
726 rank |= RF_WRITE;
727 // The TLS initialization block needs to be a single contiguous block. Place
728 // TLS sections directly before the other RELRO sections.
729 if (!(osec.flags & SHF_TLS))
730 rank |= RF_NOT_TLS;
731 if (isRelroSection(ctx, &osec))
732 osec.relro = true;
733 else
734 rank |= RF_NOT_RELRO;
735 // Place .ldata and .lbss after .bss. Making .bss closer to .text
736 // alleviates relocation overflow pressure.
737 // For -z lrodata-after-bss, place .lbss/.lrodata/.ldata after .bss.
738 // .bss/.lbss being adjacent reuses the NOBITS size optimization.
739 if (osec.flags & SHF_X86_64_LARGE && ctx.arg.emachine == EM_X86_64) {
740 rank |= ctx.arg.zLrodataAfterBss
741 ? (osec.type == SHT_NOBITS ? 1 : RF_LARGE_ALT)
742 : RF_LARGE;
746 // Within TLS sections, or within other RelRo sections, or within non-RelRo
747 // sections, place non-NOBITS sections first.
748 if (osec.type == SHT_NOBITS)
749 rank |= RF_BSS;
751 // Some architectures have additional ordering restrictions for sections
752 // within the same PT_LOAD.
753 if (ctx.arg.emachine == EM_PPC64) {
754 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
755 // that we would like to make sure appear is a specific order to maximize
756 // their coverage by a single signed 16-bit offset from the TOC base
757 // pointer.
758 StringRef name = osec.name;
759 if (name == ".got")
760 rank |= 1;
761 else if (name == ".toc")
762 rank |= 2;
765 if (ctx.arg.emachine == EM_MIPS) {
766 if (osec.name != ".got")
767 rank |= 1;
768 // All sections with SHF_MIPS_GPREL flag should be grouped together
769 // because data in these sections is addressable with a gp relative address.
770 if (osec.flags & SHF_MIPS_GPREL)
771 rank |= 2;
774 if (ctx.arg.emachine == EM_RISCV) {
775 // .sdata and .sbss are placed closer to make GP relaxation more profitable
776 // and match GNU ld.
777 StringRef name = osec.name;
778 if (name == ".sdata" || (osec.type == SHT_NOBITS && name != ".sbss"))
779 rank |= 1;
782 return rank;
785 static bool compareSections(Ctx &ctx, const SectionCommand *aCmd,
786 const SectionCommand *bCmd) {
787 const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
788 const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
790 if (a->sortRank != b->sortRank)
791 return a->sortRank < b->sortRank;
793 if (!(a->sortRank & RF_NOT_ADDR_SET))
794 return ctx.arg.sectionStartMap.lookup(a->name) <
795 ctx.arg.sectionStartMap.lookup(b->name);
796 return false;
799 void PhdrEntry::add(OutputSection *sec) {
800 lastSec = sec;
801 if (!firstSec)
802 firstSec = sec;
803 p_align = std::max(p_align, sec->addralign);
804 if (p_type == PT_LOAD)
805 sec->ptLoad = this;
808 // A statically linked position-dependent executable should only contain
809 // IRELATIVE relocations and no other dynamic relocations. Encapsulation symbols
810 // __rel[a]_iplt_{start,end} will be defined for .rel[a].dyn, to be
811 // processed by the libc runtime. Other executables or DSOs use dynamic tags
812 // instead.
813 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
814 if (ctx.arg.isPic)
815 return;
817 // __rela_iplt_{start,end} are initially defined relative to dummy section 0.
818 // We'll override ctx.out.elfHeader with relaDyn later when we are sure that
819 // .rela.dyn will be present in the output.
820 std::string name = ctx.arg.isRela ? "__rela_iplt_start" : "__rel_iplt_start";
821 ctx.sym.relaIpltStart =
822 addOptionalRegular(ctx, name, ctx.out.elfHeader.get(), 0, STV_HIDDEN);
823 name.replace(name.size() - 5, 5, "end");
824 ctx.sym.relaIpltEnd =
825 addOptionalRegular(ctx, name, ctx.out.elfHeader.get(), 0, STV_HIDDEN);
828 // This function generates assignments for predefined symbols (e.g. _end or
829 // _etext) and inserts them into the commands sequence to be processed at the
830 // appropriate time. This ensures that the value is going to be correct by the
831 // time any references to these symbols are processed and is equivalent to
832 // defining these symbols explicitly in the linker script.
833 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
834 if (ctx.sym.globalOffsetTable) {
835 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
836 // to the start of the .got or .got.plt section.
837 InputSection *sec = ctx.in.gotPlt.get();
838 if (!ctx.target->gotBaseSymInGotPlt)
839 sec = ctx.in.mipsGot ? cast<InputSection>(ctx.in.mipsGot.get())
840 : cast<InputSection>(ctx.in.got.get());
841 ctx.sym.globalOffsetTable->section = sec;
844 // .rela_iplt_{start,end} mark the start and the end of the section containing
845 // IRELATIVE relocations.
846 if (ctx.sym.relaIpltStart) {
847 auto &dyn = getIRelativeSection(ctx);
848 if (dyn.isNeeded()) {
849 ctx.sym.relaIpltStart->section = &dyn;
850 ctx.sym.relaIpltEnd->section = &dyn;
851 ctx.sym.relaIpltEnd->value = dyn.getSize();
855 PhdrEntry *last = nullptr;
856 OutputSection *lastRO = nullptr;
857 auto isLarge = [&ctx = ctx](OutputSection *osec) {
858 return ctx.arg.emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
860 for (Partition &part : ctx.partitions) {
861 for (auto &p : part.phdrs) {
862 if (p->p_type != PT_LOAD)
863 continue;
864 last = p.get();
865 if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
866 lastRO = p->lastSec;
870 if (lastRO) {
871 // _etext is the first location after the last read-only loadable segment
872 // that does not contain large sections.
873 if (ctx.sym.etext1)
874 ctx.sym.etext1->section = lastRO;
875 if (ctx.sym.etext2)
876 ctx.sym.etext2->section = lastRO;
879 if (last) {
880 // _edata points to the end of the last non-large mapped initialized
881 // section.
882 OutputSection *edata = nullptr;
883 for (OutputSection *os : ctx.outputSections) {
884 if (os->type != SHT_NOBITS && !isLarge(os))
885 edata = os;
886 if (os == last->lastSec)
887 break;
890 if (ctx.sym.edata1)
891 ctx.sym.edata1->section = edata;
892 if (ctx.sym.edata2)
893 ctx.sym.edata2->section = edata;
895 // _end is the first location after the uninitialized data region.
896 if (ctx.sym.end1)
897 ctx.sym.end1->section = last->lastSec;
898 if (ctx.sym.end2)
899 ctx.sym.end2->section = last->lastSec;
902 if (ctx.sym.bss) {
903 // On RISC-V, set __bss_start to the start of .sbss if present.
904 OutputSection *sbss =
905 ctx.arg.emachine == EM_RISCV ? findSection(ctx, ".sbss") : nullptr;
906 ctx.sym.bss->section = sbss ? sbss : findSection(ctx, ".bss");
909 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
910 // be equal to the _gp symbol's value.
911 if (ctx.sym.mipsGp) {
912 // Find GP-relative section with the lowest address
913 // and use this address to calculate default _gp value.
914 for (OutputSection *os : ctx.outputSections) {
915 if (os->flags & SHF_MIPS_GPREL) {
916 ctx.sym.mipsGp->section = os;
917 ctx.sym.mipsGp->value = 0x7ff0;
918 break;
924 // We want to find how similar two ranks are.
925 // The more branches in getSectionRank that match, the more similar they are.
926 // Since each branch corresponds to a bit flag, we can just use
927 // countLeadingZeros.
928 static int getRankProximity(OutputSection *a, SectionCommand *b) {
929 auto *osd = dyn_cast<OutputDesc>(b);
930 return (osd && osd->osec.hasInputSections)
931 ? llvm::countl_zero(a->sortRank ^ osd->osec.sortRank)
932 : -1;
935 // When placing orphan sections, we want to place them after symbol assignments
936 // so that an orphan after
937 // begin_foo = .;
938 // foo : { *(foo) }
939 // end_foo = .;
940 // doesn't break the intended meaning of the begin/end symbols.
941 // We don't want to go over sections since findOrphanPos is the
942 // one in charge of deciding the order of the sections.
943 // We don't want to go over changes to '.', since doing so in
944 // rx_sec : { *(rx_sec) }
945 // . = ALIGN(0x1000);
946 // /* The RW PT_LOAD starts here*/
947 // rw_sec : { *(rw_sec) }
948 // would mean that the RW PT_LOAD would become unaligned.
949 static bool shouldSkip(SectionCommand *cmd) {
950 if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
951 return assign->name != ".";
952 return false;
955 // We want to place orphan sections so that they share as much
956 // characteristics with their neighbors as possible. For example, if
957 // both are rw, or both are tls.
958 static SmallVectorImpl<SectionCommand *>::iterator
959 findOrphanPos(Ctx &ctx, SmallVectorImpl<SectionCommand *>::iterator b,
960 SmallVectorImpl<SectionCommand *>::iterator e) {
961 // Place non-alloc orphan sections at the end. This matches how we assign file
962 // offsets to non-alloc sections.
963 OutputSection *sec = &cast<OutputDesc>(*e)->osec;
964 if (!(sec->flags & SHF_ALLOC))
965 return e;
967 // As a special case, place .relro_padding before the SymbolAssignment using
968 // DATA_SEGMENT_RELRO_END, if present.
969 if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent()) {
970 auto i = std::find_if(b, e, [=](SectionCommand *a) {
971 if (auto *assign = dyn_cast<SymbolAssignment>(a))
972 return assign->dataSegmentRelroEnd;
973 return false;
975 if (i != e)
976 return i;
979 // Find the most similar output section as the anchor. Rank Proximity is a
980 // value in the range [-1, 32] where [0, 32] indicates potential anchors (0:
981 // least similar; 32: identical). -1 means not an anchor.
983 // In the event of proximity ties, we select the first or last section
984 // depending on whether the orphan's rank is smaller.
985 int maxP = 0;
986 auto i = e;
987 for (auto j = b; j != e; ++j) {
988 int p = getRankProximity(sec, *j);
989 if (p > maxP ||
990 (p == maxP && cast<OutputDesc>(*j)->osec.sortRank <= sec->sortRank)) {
991 maxP = p;
992 i = j;
995 if (i == e)
996 return e;
998 auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
999 auto *osd = dyn_cast<OutputDesc>(cmd);
1000 return osd && osd->osec.hasInputSections;
1003 // Then, scan backward or forward through the script for a suitable insertion
1004 // point. If i's rank is larger, the orphan section can be placed before i.
1006 // However, don't do this if custom program headers are defined. Otherwise,
1007 // adding the orphan to a previous segment can change its flags, for example,
1008 // making a read-only segment writable. If memory regions are defined, an
1009 // orphan section should continue the same region as the found section to
1010 // better resemble the behavior of GNU ld.
1011 bool mustAfter =
1012 ctx.script->hasPhdrsCommands() || !ctx.script->memoryRegions.empty();
1013 if (cast<OutputDesc>(*i)->osec.sortRank <= sec->sortRank || mustAfter) {
1014 for (auto j = ++i; j != e; ++j) {
1015 if (!isOutputSecWithInputSections(*j))
1016 continue;
1017 if (getRankProximity(sec, *j) != maxP)
1018 break;
1019 i = j + 1;
1021 } else {
1022 for (; i != b; --i)
1023 if (isOutputSecWithInputSections(i[-1]))
1024 break;
1027 // As a special case, if the orphan section is the last section, put
1028 // it at the very end, past any other commands.
1029 // This matches bfd's behavior and is convenient when the linker script fully
1030 // specifies the start of the file, but doesn't care about the end (the non
1031 // alloc sections for example).
1032 if (std::find_if(i, e, isOutputSecWithInputSections) == e)
1033 return e;
1035 while (i != e && shouldSkip(*i))
1036 ++i;
1037 return i;
1040 // Adds random priorities to sections not already in the map.
1041 static void maybeShuffle(Ctx &ctx,
1042 DenseMap<const InputSectionBase *, int> &order) {
1043 if (ctx.arg.shuffleSections.empty())
1044 return;
1046 SmallVector<InputSectionBase *, 0> matched, sections = ctx.inputSections;
1047 matched.reserve(sections.size());
1048 for (const auto &patAndSeed : ctx.arg.shuffleSections) {
1049 matched.clear();
1050 for (InputSectionBase *sec : sections)
1051 if (patAndSeed.first.match(sec->name))
1052 matched.push_back(sec);
1053 const uint32_t seed = patAndSeed.second;
1054 if (seed == UINT32_MAX) {
1055 // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1056 // section order is stable even if the number of sections changes. This is
1057 // useful to catch issues like static initialization order fiasco
1058 // reliably.
1059 std::reverse(matched.begin(), matched.end());
1060 } else {
1061 std::mt19937 g(seed ? seed : std::random_device()());
1062 llvm::shuffle(matched.begin(), matched.end(), g);
1064 size_t i = 0;
1065 for (InputSectionBase *&sec : sections)
1066 if (patAndSeed.first.match(sec->name))
1067 sec = matched[i++];
1070 // Existing priorities are < 0, so use priorities >= 0 for the missing
1071 // sections.
1072 int prio = 0;
1073 for (InputSectionBase *sec : sections) {
1074 if (order.try_emplace(sec, prio).second)
1075 ++prio;
1079 // Return section order within an InputSectionDescription.
1080 // If both --symbol-ordering-file and call graph profile are present, the order
1081 // file takes precedence, but the call graph profile is still used for symbols
1082 // that don't appear in the order file.
1083 static DenseMap<const InputSectionBase *, int> buildSectionOrder(Ctx &ctx) {
1084 DenseMap<const InputSectionBase *, int> sectionOrder;
1085 if (!ctx.arg.callGraphProfile.empty())
1086 sectionOrder = computeCallGraphProfileOrder(ctx);
1088 if (ctx.arg.symbolOrderingFile.empty())
1089 return sectionOrder;
1091 struct SymbolOrderEntry {
1092 int priority;
1093 bool present;
1096 // Build a map from symbols to their priorities. Symbols that didn't
1097 // appear in the symbol ordering file have the lowest priority 0.
1098 // All explicitly mentioned symbols have negative (higher) priorities.
1099 DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
1100 int priority = -sectionOrder.size() - ctx.arg.symbolOrderingFile.size();
1101 for (StringRef s : ctx.arg.symbolOrderingFile)
1102 symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
1104 // Build a map from sections to their priorities.
1105 auto addSym = [&](Symbol &sym) {
1106 auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
1107 if (it == symbolOrder.end())
1108 return;
1109 SymbolOrderEntry &ent = it->second;
1110 ent.present = true;
1112 maybeWarnUnorderableSymbol(ctx, &sym);
1114 if (auto *d = dyn_cast<Defined>(&sym)) {
1115 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1116 int &priority = sectionOrder[cast<InputSectionBase>(sec)];
1117 priority = std::min(priority, ent.priority);
1122 // We want both global and local symbols. We get the global ones from the
1123 // symbol table and iterate the object files for the local ones.
1124 for (Symbol *sym : ctx.symtab->getSymbols())
1125 addSym(*sym);
1127 for (ELFFileBase *file : ctx.objectFiles)
1128 for (Symbol *sym : file->getLocalSymbols())
1129 addSym(*sym);
1131 if (ctx.arg.warnSymbolOrdering)
1132 for (auto orderEntry : symbolOrder)
1133 if (!orderEntry.second.present)
1134 Warn(ctx) << "symbol ordering file: no such symbol: "
1135 << orderEntry.first.val();
1137 return sectionOrder;
1140 // Sorts the sections in ISD according to the provided section order.
1141 static void
1142 sortISDBySectionOrder(Ctx &ctx, InputSectionDescription *isd,
1143 const DenseMap<const InputSectionBase *, int> &order,
1144 bool executableOutputSection) {
1145 SmallVector<InputSection *, 0> unorderedSections;
1146 SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
1147 uint64_t unorderedSize = 0;
1148 uint64_t totalSize = 0;
1150 for (InputSection *isec : isd->sections) {
1151 if (executableOutputSection)
1152 totalSize += isec->getSize();
1153 auto i = order.find(isec);
1154 if (i == order.end()) {
1155 unorderedSections.push_back(isec);
1156 unorderedSize += isec->getSize();
1157 continue;
1159 orderedSections.push_back({isec, i->second});
1161 llvm::sort(orderedSections, llvm::less_second());
1163 // Find an insertion point for the ordered section list in the unordered
1164 // section list. On targets with limited-range branches, this is the mid-point
1165 // of the unordered section list. This decreases the likelihood that a range
1166 // extension thunk will be needed to enter or exit the ordered region. If the
1167 // ordered section list is a list of hot functions, we can generally expect
1168 // the ordered functions to be called more often than the unordered functions,
1169 // making it more likely that any particular call will be within range, and
1170 // therefore reducing the number of thunks required.
1172 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1173 // If the layout is:
1175 // 8MB hot
1176 // 32MB cold
1178 // only the first 8-16MB of the cold code (depending on which hot function it
1179 // is actually calling) can call the hot code without a range extension thunk.
1180 // However, if we use this layout:
1182 // 16MB cold
1183 // 8MB hot
1184 // 16MB cold
1186 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1187 // of the second block of cold code can call the hot code without a thunk. So
1188 // we effectively double the amount of code that could potentially call into
1189 // the hot code without a thunk.
1191 // The above is not necessary if total size of input sections in this "isd"
1192 // is small. Note that we assume all input sections are executable if the
1193 // output section is executable (which is not always true but supposed to
1194 // cover most cases).
1195 size_t insPt = 0;
1196 if (executableOutputSection && !orderedSections.empty() &&
1197 ctx.target->getThunkSectionSpacing() &&
1198 totalSize >= ctx.target->getThunkSectionSpacing()) {
1199 uint64_t unorderedPos = 0;
1200 for (; insPt != unorderedSections.size(); ++insPt) {
1201 unorderedPos += unorderedSections[insPt]->getSize();
1202 if (unorderedPos > unorderedSize / 2)
1203 break;
1207 isd->sections.clear();
1208 for (InputSection *isec : ArrayRef(unorderedSections).slice(0, insPt))
1209 isd->sections.push_back(isec);
1210 for (std::pair<InputSection *, int> p : orderedSections)
1211 isd->sections.push_back(p.first);
1212 for (InputSection *isec : ArrayRef(unorderedSections).slice(insPt))
1213 isd->sections.push_back(isec);
1216 static void sortSection(Ctx &ctx, OutputSection &osec,
1217 const DenseMap<const InputSectionBase *, int> &order) {
1218 StringRef name = osec.name;
1220 // Never sort these.
1221 if (name == ".init" || name == ".fini")
1222 return;
1224 // Sort input sections by priority using the list provided by
1225 // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1226 // digit radix sort. The sections may be sorted stably again by a more
1227 // significant key.
1228 if (!order.empty())
1229 for (SectionCommand *b : osec.commands)
1230 if (auto *isd = dyn_cast<InputSectionDescription>(b))
1231 sortISDBySectionOrder(ctx, isd, order, osec.flags & SHF_EXECINSTR);
1233 if (ctx.script->hasSectionsCommand)
1234 return;
1236 if (name == ".init_array" || name == ".fini_array") {
1237 osec.sortInitFini();
1238 } else if (name == ".ctors" || name == ".dtors") {
1239 osec.sortCtorsDtors();
1240 } else if (ctx.arg.emachine == EM_PPC64 && name == ".toc") {
1241 // .toc is allocated just after .got and is accessed using GOT-relative
1242 // relocations. Object files compiled with small code model have an
1243 // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1244 // To reduce the risk of relocation overflow, .toc contents are sorted so
1245 // that sections having smaller relocation offsets are at beginning of .toc
1246 assert(osec.commands.size() == 1);
1247 auto *isd = cast<InputSectionDescription>(osec.commands[0]);
1248 llvm::stable_sort(isd->sections,
1249 [](const InputSection *a, const InputSection *b) -> bool {
1250 return a->file->ppc64SmallCodeModelTocRelocs &&
1251 !b->file->ppc64SmallCodeModelTocRelocs;
1256 // Sort sections within each InputSectionDescription.
1257 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1258 // Assign negative priorities.
1259 DenseMap<const InputSectionBase *, int> order = buildSectionOrder(ctx);
1260 // Assign non-negative priorities due to --shuffle-sections.
1261 maybeShuffle(ctx, order);
1262 for (SectionCommand *cmd : ctx.script->sectionCommands)
1263 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1264 sortSection(ctx, osd->osec, order);
1267 template <class ELFT> void Writer<ELFT>::sortSections() {
1268 llvm::TimeTraceScope timeScope("Sort sections");
1270 // Don't sort if using -r. It is not necessary and we want to preserve the
1271 // relative order for SHF_LINK_ORDER sections.
1272 if (ctx.arg.relocatable) {
1273 ctx.script->adjustOutputSections();
1274 return;
1277 sortInputSections();
1279 for (SectionCommand *cmd : ctx.script->sectionCommands)
1280 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1281 osd->osec.sortRank = getSectionRank(ctx, osd->osec);
1282 if (!ctx.script->hasSectionsCommand) {
1283 // OutputDescs are mostly contiguous, but may be interleaved with
1284 // SymbolAssignments in the presence of INSERT commands.
1285 auto mid = std::stable_partition(
1286 ctx.script->sectionCommands.begin(), ctx.script->sectionCommands.end(),
1287 [](SectionCommand *cmd) { return isa<OutputDesc>(cmd); });
1288 std::stable_sort(
1289 ctx.script->sectionCommands.begin(), mid,
1290 [&ctx = ctx](auto *l, auto *r) { return compareSections(ctx, l, r); });
1293 // Process INSERT commands and update output section attributes. From this
1294 // point onwards the order of script->sectionCommands is fixed.
1295 ctx.script->processInsertCommands();
1296 ctx.script->adjustOutputSections();
1298 if (ctx.script->hasSectionsCommand)
1299 sortOrphanSections();
1301 ctx.script->adjustSectionsAfterSorting();
1304 template <class ELFT> void Writer<ELFT>::sortOrphanSections() {
1305 // Orphan sections are sections present in the input files which are
1306 // not explicitly placed into the output file by the linker script.
1308 // The sections in the linker script are already in the correct
1309 // order. We have to figuere out where to insert the orphan
1310 // sections.
1312 // The order of the sections in the script is arbitrary and may not agree with
1313 // compareSections. This means that we cannot easily define a strict weak
1314 // ordering. To see why, consider a comparison of a section in the script and
1315 // one not in the script. We have a two simple options:
1316 // * Make them equivalent (a is not less than b, and b is not less than a).
1317 // The problem is then that equivalence has to be transitive and we can
1318 // have sections a, b and c with only b in a script and a less than c
1319 // which breaks this property.
1320 // * Use compareSectionsNonScript. Given that the script order doesn't have
1321 // to match, we can end up with sections a, b, c, d where b and c are in the
1322 // script and c is compareSectionsNonScript less than b. In which case d
1323 // can be equivalent to c, a to b and d < a. As a concrete example:
1324 // .a (rx) # not in script
1325 // .b (rx) # in script
1326 // .c (ro) # in script
1327 // .d (ro) # not in script
1329 // The way we define an order then is:
1330 // * Sort only the orphan sections. They are in the end right now.
1331 // * Move each orphan section to its preferred position. We try
1332 // to put each section in the last position where it can share
1333 // a PT_LOAD.
1335 // There is some ambiguity as to where exactly a new entry should be
1336 // inserted, because Commands contains not only output section
1337 // commands but also other types of commands such as symbol assignment
1338 // expressions. There's no correct answer here due to the lack of the
1339 // formal specification of the linker script. We use heuristics to
1340 // determine whether a new output command should be added before or
1341 // after another commands. For the details, look at shouldSkip
1342 // function.
1344 auto i = ctx.script->sectionCommands.begin();
1345 auto e = ctx.script->sectionCommands.end();
1346 auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
1347 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1348 return osd->osec.sectionIndex == UINT32_MAX;
1349 return false;
1352 // Sort the orphan sections.
1353 std::stable_sort(nonScriptI, e, [&ctx = ctx](auto *l, auto *r) {
1354 return compareSections(ctx, l, r);
1357 // As a horrible special case, skip the first . assignment if it is before any
1358 // section. We do this because it is common to set a load address by starting
1359 // the script with ". = 0xabcd" and the expectation is that every section is
1360 // after that.
1361 auto firstSectionOrDotAssignment =
1362 std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
1363 if (firstSectionOrDotAssignment != e &&
1364 isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1365 ++firstSectionOrDotAssignment;
1366 i = firstSectionOrDotAssignment;
1368 while (nonScriptI != e) {
1369 auto pos = findOrphanPos(ctx, i, nonScriptI);
1370 OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
1372 // As an optimization, find all sections with the same sort rank
1373 // and insert them with one rotate.
1374 unsigned rank = orphan->sortRank;
1375 auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
1376 return cast<OutputDesc>(cmd)->osec.sortRank != rank;
1378 std::rotate(pos, nonScriptI, end);
1379 nonScriptI = end;
1383 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1384 InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1385 InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1386 // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1387 // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1388 if (!la || !lb)
1389 return la && !lb;
1390 OutputSection *aOut = la->getParent();
1391 OutputSection *bOut = lb->getParent();
1393 if (aOut == bOut)
1394 return la->outSecOff < lb->outSecOff;
1395 if (aOut->addr == bOut->addr)
1396 return aOut->sectionIndex < bOut->sectionIndex;
1397 return aOut->addr < bOut->addr;
1400 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1401 llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1402 for (OutputSection *sec : ctx.outputSections) {
1403 if (!(sec->flags & SHF_LINK_ORDER))
1404 continue;
1406 // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1407 // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1408 if (!ctx.arg.relocatable && ctx.arg.emachine == EM_ARM &&
1409 sec->type == SHT_ARM_EXIDX)
1410 continue;
1412 // Link order may be distributed across several InputSectionDescriptions.
1413 // Sorting is performed separately.
1414 SmallVector<InputSection **, 0> scriptSections;
1415 SmallVector<InputSection *, 0> sections;
1416 for (SectionCommand *cmd : sec->commands) {
1417 auto *isd = dyn_cast<InputSectionDescription>(cmd);
1418 if (!isd)
1419 continue;
1420 bool hasLinkOrder = false;
1421 scriptSections.clear();
1422 sections.clear();
1423 for (InputSection *&isec : isd->sections) {
1424 if (isec->flags & SHF_LINK_ORDER) {
1425 InputSection *link = isec->getLinkOrderDep();
1426 if (link && !link->getParent())
1427 ErrAlways(ctx) << isec << ": sh_link points to discarded section "
1428 << link;
1429 hasLinkOrder = true;
1431 scriptSections.push_back(&isec);
1432 sections.push_back(isec);
1434 if (hasLinkOrder && errCount(ctx) == 0) {
1435 llvm::stable_sort(sections, compareByFilePosition);
1436 for (int i = 0, n = sections.size(); i != n; ++i)
1437 *scriptSections[i] = sections[i];
1443 static void finalizeSynthetic(Ctx &ctx, SyntheticSection *sec) {
1444 if (sec && sec->isNeeded() && sec->getParent()) {
1445 llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1446 sec->finalizeContents();
1450 static bool canInsertPadding(OutputSection *sec) {
1451 StringRef s = sec->name;
1452 return s == ".bss" || s == ".data" || s == ".data.rel.ro" || s == ".lbss" ||
1453 s == ".ldata" || s == ".lrodata" || s == ".ltext" || s == ".rodata" ||
1454 s.starts_with(".text");
1457 static void randomizeSectionPadding(Ctx &ctx) {
1458 std::mt19937 g(*ctx.arg.randomizeSectionPadding);
1459 PhdrEntry *curPtLoad = nullptr;
1460 for (OutputSection *os : ctx.outputSections) {
1461 if (!canInsertPadding(os))
1462 continue;
1463 for (SectionCommand *bc : os->commands) {
1464 if (auto *isd = dyn_cast<InputSectionDescription>(bc)) {
1465 SmallVector<InputSection *, 0> tmp;
1466 if (os->ptLoad != curPtLoad) {
1467 tmp.push_back(make<RandomizePaddingSection>(
1468 ctx, g() % ctx.arg.maxPageSize, os));
1469 curPtLoad = os->ptLoad;
1471 for (InputSection *isec : isd->sections) {
1472 // Probability of inserting padding is 1 in 16.
1473 if (g() % 16 == 0)
1474 tmp.push_back(
1475 make<RandomizePaddingSection>(ctx, isec->addralign, os));
1476 tmp.push_back(isec);
1478 isd->sections = std::move(tmp);
1484 // We need to generate and finalize the content that depends on the address of
1485 // InputSections. As the generation of the content may also alter InputSection
1486 // addresses we must converge to a fixed point. We do that here. See the comment
1487 // in Writer<ELFT>::finalizeSections().
1488 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1489 llvm::TimeTraceScope timeScope("Finalize address dependent content");
1490 AArch64Err843419Patcher a64p(ctx);
1491 ARMErr657417Patcher a32p(ctx);
1492 ctx.script->assignAddresses();
1494 // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1495 // do require the relative addresses of OutputSections because linker scripts
1496 // can assign Virtual Addresses to OutputSections that are not monotonically
1497 // increasing. Anything here must be repeatable, since spilling may change
1498 // section order.
1499 const auto finalizeOrderDependentContent = [this] {
1500 for (Partition &part : ctx.partitions)
1501 finalizeSynthetic(ctx, part.armExidx.get());
1502 resolveShfLinkOrder();
1504 finalizeOrderDependentContent();
1506 // Converts call x@GDPLT to call __tls_get_addr
1507 if (ctx.arg.emachine == EM_HEXAGON)
1508 hexagonTLSSymbolUpdate(ctx);
1510 if (ctx.arg.randomizeSectionPadding)
1511 randomizeSectionPadding(ctx);
1513 uint32_t pass = 0, assignPasses = 0;
1514 for (;;) {
1515 bool changed = ctx.target->needsThunks
1516 ? tc.createThunks(pass, ctx.outputSections)
1517 : ctx.target->relaxOnce(pass);
1518 bool spilled = ctx.script->spillSections();
1519 changed |= spilled;
1520 ++pass;
1522 // With Thunk Size much smaller than branch range we expect to
1523 // converge quickly; if we get to 30 something has gone wrong.
1524 if (changed && pass >= 30) {
1525 Err(ctx) << (ctx.target->needsThunks ? "thunk creation not converged"
1526 : "relaxation not converged");
1527 break;
1530 if (ctx.arg.fixCortexA53Errata843419) {
1531 if (changed)
1532 ctx.script->assignAddresses();
1533 changed |= a64p.createFixes();
1535 if (ctx.arg.fixCortexA8) {
1536 if (changed)
1537 ctx.script->assignAddresses();
1538 changed |= a32p.createFixes();
1541 finalizeSynthetic(ctx, ctx.in.got.get());
1542 if (ctx.in.mipsGot)
1543 ctx.in.mipsGot->updateAllocSize(ctx);
1545 for (Partition &part : ctx.partitions) {
1546 // The R_AARCH64_AUTH_RELATIVE has a smaller addend field as bits [63:32]
1547 // encode the signing schema. We've put relocations in .relr.auth.dyn
1548 // during RelocationScanner::processAux, but the target VA for some of
1549 // them might be wider than 32 bits. We can only know the final VA at this
1550 // point, so move relocations with large values from .relr.auth.dyn to
1551 // .rela.dyn. See also AArch64::relocate.
1552 if (part.relrAuthDyn) {
1553 auto it = llvm::remove_if(
1554 part.relrAuthDyn->relocs, [this, &part](const RelativeReloc &elem) {
1555 const Relocation &reloc = elem.inputSec->relocs()[elem.relocIdx];
1556 if (isInt<32>(reloc.sym->getVA(ctx, reloc.addend)))
1557 return false;
1558 part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, elem.inputSec,
1559 reloc.offset,
1560 DynamicReloc::AddendOnlyWithTargetVA,
1561 *reloc.sym, reloc.addend, R_ABS});
1562 return true;
1564 changed |= (it != part.relrAuthDyn->relocs.end());
1565 part.relrAuthDyn->relocs.erase(it, part.relrAuthDyn->relocs.end());
1567 if (part.relaDyn)
1568 changed |= part.relaDyn->updateAllocSize(ctx);
1569 if (part.relrDyn)
1570 changed |= part.relrDyn->updateAllocSize(ctx);
1571 if (part.relrAuthDyn)
1572 changed |= part.relrAuthDyn->updateAllocSize(ctx);
1573 if (part.memtagGlobalDescriptors)
1574 changed |= part.memtagGlobalDescriptors->updateAllocSize(ctx);
1577 std::pair<const OutputSection *, const Defined *> changes =
1578 ctx.script->assignAddresses();
1579 if (!changed) {
1580 // Some symbols may be dependent on section addresses. When we break the
1581 // loop, the symbol values are finalized because a previous
1582 // assignAddresses() finalized section addresses.
1583 if (!changes.first && !changes.second)
1584 break;
1585 if (++assignPasses == 5) {
1586 if (changes.first)
1587 Err(ctx) << "address (0x" << Twine::utohexstr(changes.first->addr)
1588 << ") of section '" << changes.first->name
1589 << "' does not converge";
1590 if (changes.second)
1591 Err(ctx) << "assignment to symbol " << changes.second
1592 << " does not converge";
1593 break;
1595 } else if (spilled) {
1596 // Spilling can change relative section order.
1597 finalizeOrderDependentContent();
1600 if (!ctx.arg.relocatable)
1601 ctx.target->finalizeRelax(pass);
1603 if (ctx.arg.relocatable)
1604 for (OutputSection *sec : ctx.outputSections)
1605 sec->addr = 0;
1607 // If addrExpr is set, the address may not be a multiple of the alignment.
1608 // Warn because this is error-prone.
1609 for (SectionCommand *cmd : ctx.script->sectionCommands)
1610 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1611 OutputSection *osec = &osd->osec;
1612 if (osec->addr % osec->addralign != 0)
1613 Warn(ctx) << "address (0x" << Twine::utohexstr(osec->addr)
1614 << ") of section " << osec->name
1615 << " is not a multiple of alignment (" << osec->addralign
1616 << ")";
1619 // Sizes are no longer allowed to grow, so all allowable spills have been
1620 // taken. Remove any leftover potential spills.
1621 ctx.script->erasePotentialSpillSections();
1624 // If Input Sections have been shrunk (basic block sections) then
1625 // update symbol values and sizes associated with these sections. With basic
1626 // block sections, input sections can shrink when the jump instructions at
1627 // the end of the section are relaxed.
1628 static void fixSymbolsAfterShrinking(Ctx &ctx) {
1629 for (InputFile *File : ctx.objectFiles) {
1630 parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1631 auto *def = dyn_cast<Defined>(Sym);
1632 if (!def)
1633 return;
1635 const SectionBase *sec = def->section;
1636 if (!sec)
1637 return;
1639 const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1640 if (!inputSec || !inputSec->bytesDropped)
1641 return;
1643 const size_t OldSize = inputSec->content().size();
1644 const size_t NewSize = OldSize - inputSec->bytesDropped;
1646 if (def->value > NewSize && def->value <= OldSize) {
1647 LLVM_DEBUG(llvm::dbgs()
1648 << "Moving symbol " << Sym->getName() << " from "
1649 << def->value << " to "
1650 << def->value - inputSec->bytesDropped << " bytes\n");
1651 def->value -= inputSec->bytesDropped;
1652 return;
1655 if (def->value + def->size > NewSize && def->value <= OldSize &&
1656 def->value + def->size <= OldSize) {
1657 LLVM_DEBUG(llvm::dbgs()
1658 << "Shrinking symbol " << Sym->getName() << " from "
1659 << def->size << " to " << def->size - inputSec->bytesDropped
1660 << " bytes\n");
1661 def->size -= inputSec->bytesDropped;
1667 // If basic block sections exist, there are opportunities to delete fall thru
1668 // jumps and shrink jump instructions after basic block reordering. This
1669 // relaxation pass does that. It is only enabled when --optimize-bb-jumps
1670 // option is used.
1671 template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1672 assert(ctx.arg.optimizeBBJumps);
1673 SmallVector<InputSection *, 0> storage;
1675 ctx.script->assignAddresses();
1676 // For every output section that has executable input sections, this
1677 // does the following:
1678 // 1. Deletes all direct jump instructions in input sections that
1679 // jump to the following section as it is not required.
1680 // 2. If there are two consecutive jump instructions, it checks
1681 // if they can be flipped and one can be deleted.
1682 for (OutputSection *osec : ctx.outputSections) {
1683 if (!(osec->flags & SHF_EXECINSTR))
1684 continue;
1685 ArrayRef<InputSection *> sections = getInputSections(*osec, storage);
1686 size_t numDeleted = 0;
1687 // Delete all fall through jump instructions. Also, check if two
1688 // consecutive jump instructions can be flipped so that a fall
1689 // through jmp instruction can be deleted.
1690 for (size_t i = 0, e = sections.size(); i != e; ++i) {
1691 InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1692 InputSection &sec = *sections[i];
1693 numDeleted += ctx.target->deleteFallThruJmpInsn(sec, sec.file, next);
1695 if (numDeleted > 0) {
1696 ctx.script->assignAddresses();
1697 LLVM_DEBUG(llvm::dbgs()
1698 << "Removing " << numDeleted << " fall through jumps\n");
1702 fixSymbolsAfterShrinking(ctx);
1704 for (OutputSection *osec : ctx.outputSections)
1705 for (InputSection *is : getInputSections(*osec, storage))
1706 is->trim();
1709 // In order to allow users to manipulate linker-synthesized sections,
1710 // we had to add synthetic sections to the input section list early,
1711 // even before we make decisions whether they are needed. This allows
1712 // users to write scripts like this: ".mygot : { .got }".
1714 // Doing it has an unintended side effects. If it turns out that we
1715 // don't need a .got (for example) at all because there's no
1716 // relocation that needs a .got, we don't want to emit .got.
1718 // To deal with the above problem, this function is called after
1719 // scanRelocations is called to remove synthetic sections that turn
1720 // out to be empty.
1721 static void removeUnusedSyntheticSections(Ctx &ctx) {
1722 // All input synthetic sections that can be empty are placed after
1723 // all regular ones. Reverse iterate to find the first synthetic section
1724 // after a non-synthetic one which will be our starting point.
1725 auto start =
1726 llvm::find_if(llvm::reverse(ctx.inputSections), [](InputSectionBase *s) {
1727 return !isa<SyntheticSection>(s);
1728 }).base();
1730 // Remove unused synthetic sections from ctx.inputSections;
1731 DenseSet<InputSectionBase *> unused;
1732 auto end =
1733 std::remove_if(start, ctx.inputSections.end(), [&](InputSectionBase *s) {
1734 auto *sec = cast<SyntheticSection>(s);
1735 if (sec->getParent() && sec->isNeeded())
1736 return false;
1737 // .relr.auth.dyn relocations may be moved to .rela.dyn in
1738 // finalizeAddressDependentContent, making .rela.dyn no longer empty.
1739 // Conservatively keep .rela.dyn. .relr.auth.dyn can be made empty, but
1740 // we would fail to remove it here.
1741 if (ctx.arg.emachine == EM_AARCH64 && ctx.arg.relrPackDynRelocs &&
1742 sec == ctx.mainPart->relaDyn.get())
1743 return false;
1744 unused.insert(sec);
1745 return true;
1747 ctx.inputSections.erase(end, ctx.inputSections.end());
1749 // Remove unused synthetic sections from the corresponding input section
1750 // description and orphanSections.
1751 for (auto *sec : unused)
1752 if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
1753 for (SectionCommand *cmd : osec->commands)
1754 if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
1755 llvm::erase_if(isd->sections, [&](InputSection *isec) {
1756 return unused.count(isec);
1758 llvm::erase_if(ctx.script->orphanSections, [&](const InputSectionBase *sec) {
1759 return unused.count(sec);
1763 // Create output section objects and add them to OutputSections.
1764 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1765 if (!ctx.arg.relocatable) {
1766 ctx.out.preinitArray = findSection(ctx, ".preinit_array");
1767 ctx.out.initArray = findSection(ctx, ".init_array");
1768 ctx.out.finiArray = findSection(ctx, ".fini_array");
1770 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1771 // symbols for sections, so that the runtime can get the start and end
1772 // addresses of each section by section name. Add such symbols.
1773 addStartEndSymbols();
1774 for (SectionCommand *cmd : ctx.script->sectionCommands)
1775 if (auto *osd = dyn_cast<OutputDesc>(cmd))
1776 addStartStopSymbols(osd->osec);
1778 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1779 // It should be okay as no one seems to care about the type.
1780 // Even the author of gold doesn't remember why gold behaves that way.
1781 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1782 if (ctx.mainPart->dynamic->parent) {
1783 Symbol *s = ctx.symtab->addSymbol(Defined{
1784 ctx, ctx.internalFile, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1785 /*value=*/0, /*size=*/0, ctx.mainPart->dynamic.get()});
1786 s->isUsedInRegularObj = true;
1789 // Define __rel[a]_iplt_{start,end} symbols if needed.
1790 addRelIpltSymbols();
1792 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1793 // should only be defined in an executable. If .sdata does not exist, its
1794 // value/section does not matter but it has to be relative, so set its
1795 // st_shndx arbitrarily to 1 (ctx.out.elfHeader).
1796 if (ctx.arg.emachine == EM_RISCV) {
1797 if (!ctx.arg.shared) {
1798 OutputSection *sec = findSection(ctx, ".sdata");
1799 addOptionalRegular(ctx, "__global_pointer$",
1800 sec ? sec : ctx.out.elfHeader.get(), 0x800,
1801 STV_DEFAULT);
1802 // Set riscvGlobalPointer to be used by the optional global pointer
1803 // relaxation.
1804 if (ctx.arg.relaxGP) {
1805 Symbol *s = ctx.symtab->find("__global_pointer$");
1806 if (s && s->isDefined())
1807 ctx.sym.riscvGlobalPointer = cast<Defined>(s);
1812 if (ctx.arg.emachine == EM_386 || ctx.arg.emachine == EM_X86_64) {
1813 // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1814 // way that:
1816 // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1817 // computes 0.
1818 // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address
1819 // in the TLS block).
1821 // 2) is special cased in @tpoff computation. To satisfy 1), we define it
1822 // as an absolute symbol of zero. This is different from GNU linkers which
1823 // define _TLS_MODULE_BASE_ relative to the first TLS section.
1824 Symbol *s = ctx.symtab->find("_TLS_MODULE_BASE_");
1825 if (s && s->isUndefined()) {
1826 s->resolve(ctx, Defined{ctx, ctx.internalFile, StringRef(), STB_GLOBAL,
1827 STV_HIDDEN, STT_TLS, /*value=*/0, 0,
1828 /*section=*/nullptr});
1829 ctx.sym.tlsModuleBase = cast<Defined>(s);
1833 // This responsible for splitting up .eh_frame section into
1834 // pieces. The relocation scan uses those pieces, so this has to be
1835 // earlier.
1837 llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1838 for (Partition &part : ctx.partitions)
1839 finalizeSynthetic(ctx, part.ehFrame.get());
1843 // If the previous code block defines any non-hidden symbols (e.g.
1844 // __global_pointer$), they may be exported.
1845 if (ctx.hasDynsym && ctx.arg.exportDynamic)
1846 for (Symbol *sym : ctx.synthesizedSymbols)
1847 if (sym->computeBinding(ctx) != STB_LOCAL)
1848 sym->isExported = true;
1850 demoteSymbolsAndComputeIsPreemptible(ctx);
1852 if (ctx.arg.copyRelocs && ctx.arg.discard != DiscardPolicy::None)
1853 markUsedLocalSymbols<ELFT>(ctx);
1854 demoteAndCopyLocalSymbols(ctx);
1856 if (ctx.arg.copyRelocs)
1857 addSectionSymbols();
1859 // Change values of linker-script-defined symbols from placeholders (assigned
1860 // by declareSymbols) to actual definitions.
1861 ctx.script->processSymbolAssignments();
1863 if (!ctx.arg.relocatable) {
1864 llvm::TimeTraceScope timeScope("Scan relocations");
1865 // Scan relocations. This must be done after every symbol is declared so
1866 // that we can correctly decide if a dynamic relocation is needed. This is
1867 // called after processSymbolAssignments() because it needs to know whether
1868 // a linker-script-defined symbol is absolute.
1869 scanRelocations<ELFT>(ctx);
1870 reportUndefinedSymbols(ctx);
1871 postScanRelocations(ctx);
1873 if (ctx.in.plt && ctx.in.plt->isNeeded())
1874 ctx.in.plt->addSymbols();
1875 if (ctx.in.iplt && ctx.in.iplt->isNeeded())
1876 ctx.in.iplt->addSymbols();
1878 if (ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1879 auto diag =
1880 ctx.arg.unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError &&
1881 !ctx.arg.noinhibitExec
1882 ? DiagLevel::Err
1883 : DiagLevel::Warn;
1884 // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1885 // entries are seen. These cases would otherwise lead to runtime errors
1886 // reported by the dynamic linker.
1888 // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker
1889 // to catch more cases. That is too much for us. Our approach resembles
1890 // the one used in ld.gold, achieves a good balance to be useful but not
1891 // too smart.
1893 // If a DSO reference is resolved by a SharedSymbol, but the SharedSymbol
1894 // is overridden by a hidden visibility Defined (which is later discarded
1895 // due to GC), don't report the diagnostic. However, this may indicate an
1896 // unintended SharedSymbol.
1897 for (SharedFile *file : ctx.sharedFiles) {
1898 bool allNeededIsKnown =
1899 llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1900 return ctx.symtab->soNames.count(CachedHashStringRef(needed));
1902 if (!allNeededIsKnown)
1903 continue;
1904 for (Symbol *sym : file->requiredSymbols) {
1905 if (sym->dsoDefined)
1906 continue;
1907 if (sym->isUndefined() && !sym->isWeak()) {
1908 ELFSyncStream(ctx, diag)
1909 << "undefined reference: " << sym << "\n>>> referenced by "
1910 << file << " (disallowed by --no-allow-shlib-undefined)";
1911 } else if (sym->isDefined() &&
1912 sym->computeBinding(ctx) == STB_LOCAL) {
1913 ELFSyncStream(ctx, diag)
1914 << "non-exported symbol '" << sym << "' in '" << sym->file
1915 << "' is referenced by DSO '" << file << "'";
1923 llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1924 // Now that we have defined all possible global symbols including linker-
1925 // synthesized ones. Visit all symbols to give the finishing touches.
1926 for (Symbol *sym : ctx.symtab->getSymbols()) {
1927 if (!sym->isUsedInRegularObj || !includeInSymtab(ctx, *sym))
1928 continue;
1929 if (!ctx.arg.relocatable)
1930 sym->binding = sym->computeBinding(ctx);
1931 if (ctx.in.symTab)
1932 ctx.in.symTab->addSymbol(sym);
1934 // computeBinding might localize a linker-synthesized hidden symbol
1935 // (e.g. __global_pointer$) that was considered exported.
1936 if ((sym->isExported || sym->isPreemptible) && !sym->isLocal()) {
1937 ctx.partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1938 if (auto *file = dyn_cast<SharedFile>(sym->file))
1939 if (file->isNeeded && !sym->isUndefined())
1940 addVerneed(ctx, *sym);
1944 // We also need to scan the dynamic relocation tables of the other
1945 // partitions and add any referenced symbols to the partition's dynsym.
1946 for (Partition &part :
1947 MutableArrayRef<Partition>(ctx.partitions).slice(1)) {
1948 DenseSet<Symbol *> syms;
1949 for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1950 syms.insert(e.sym);
1951 for (DynamicReloc &reloc : part.relaDyn->relocs)
1952 if (reloc.sym && reloc.needsDynSymIndex() &&
1953 syms.insert(reloc.sym).second)
1954 part.dynSymTab->addSymbol(reloc.sym);
1958 if (ctx.in.mipsGot)
1959 ctx.in.mipsGot->build();
1961 removeUnusedSyntheticSections(ctx);
1962 ctx.script->diagnoseOrphanHandling();
1963 ctx.script->diagnoseMissingSGSectionAddress();
1965 sortSections();
1967 // Create a list of OutputSections, assign sectionIndex, and populate
1968 // ctx.in.shStrTab. If -z nosectionheader is specified, drop non-ALLOC
1969 // sections.
1970 for (SectionCommand *cmd : ctx.script->sectionCommands)
1971 if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1972 OutputSection *osec = &osd->osec;
1973 if (!ctx.in.shStrTab && !(osec->flags & SHF_ALLOC))
1974 continue;
1975 ctx.outputSections.push_back(osec);
1976 osec->sectionIndex = ctx.outputSections.size();
1977 if (ctx.in.shStrTab)
1978 osec->shName = ctx.in.shStrTab->addString(osec->name);
1981 // Prefer command line supplied address over other constraints.
1982 for (OutputSection *sec : ctx.outputSections) {
1983 auto i = ctx.arg.sectionStartMap.find(sec->name);
1984 if (i != ctx.arg.sectionStartMap.end())
1985 sec->addrExpr = [=] { return i->second; };
1988 // With the ctx.outputSections available check for GDPLT relocations
1989 // and add __tls_get_addr symbol if needed.
1990 if (ctx.arg.emachine == EM_HEXAGON &&
1991 hexagonNeedsTLSSymbol(ctx.outputSections)) {
1992 Symbol *sym =
1993 ctx.symtab->addSymbol(Undefined{ctx.internalFile, "__tls_get_addr",
1994 STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
1995 sym->isPreemptible = true;
1996 ctx.partitions[0].dynSymTab->addSymbol(sym);
1999 // This is a bit of a hack. A value of 0 means undef, so we set it
2000 // to 1 to make __ehdr_start defined. The section number is not
2001 // particularly relevant.
2002 ctx.out.elfHeader->sectionIndex = 1;
2003 ctx.out.elfHeader->size = sizeof(typename ELFT::Ehdr);
2005 // Binary and relocatable output does not have PHDRS.
2006 // The headers have to be created before finalize as that can influence the
2007 // image base and the dynamic section on mips includes the image base.
2008 if (!ctx.arg.relocatable && !ctx.arg.oFormatBinary) {
2009 for (Partition &part : ctx.partitions) {
2010 part.phdrs = ctx.script->hasPhdrsCommands() ? ctx.script->createPhdrs()
2011 : createPhdrs(part);
2012 if (ctx.arg.emachine == EM_ARM) {
2013 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2014 addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2016 if (ctx.arg.emachine == EM_MIPS) {
2017 // Add separate segments for MIPS-specific sections.
2018 addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2019 addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2020 addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2022 if (ctx.arg.emachine == EM_RISCV)
2023 addPhdrForSection(part, SHT_RISCV_ATTRIBUTES, PT_RISCV_ATTRIBUTES,
2024 PF_R);
2026 ctx.out.programHeaders->size =
2027 sizeof(Elf_Phdr) * ctx.mainPart->phdrs.size();
2029 // Find the TLS segment. This happens before the section layout loop so that
2030 // Android relocation packing can look up TLS symbol addresses. We only need
2031 // to care about the main partition here because all TLS symbols were moved
2032 // to the main partition (see MarkLive.cpp).
2033 for (auto &p : ctx.mainPart->phdrs)
2034 if (p->p_type == PT_TLS)
2035 ctx.tlsPhdr = p.get();
2038 // Some symbols are defined in term of program headers. Now that we
2039 // have the headers, we can find out which sections they point to.
2040 setReservedSymbolSections();
2042 if (ctx.script->noCrossRefs.size()) {
2043 llvm::TimeTraceScope timeScope("Check NOCROSSREFS");
2044 checkNoCrossRefs<ELFT>(ctx);
2048 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2050 finalizeSynthetic(ctx, ctx.in.bss.get());
2051 finalizeSynthetic(ctx, ctx.in.bssRelRo.get());
2052 finalizeSynthetic(ctx, ctx.in.symTabShndx.get());
2053 finalizeSynthetic(ctx, ctx.in.shStrTab.get());
2054 finalizeSynthetic(ctx, ctx.in.strTab.get());
2055 finalizeSynthetic(ctx, ctx.in.got.get());
2056 finalizeSynthetic(ctx, ctx.in.mipsGot.get());
2057 finalizeSynthetic(ctx, ctx.in.igotPlt.get());
2058 finalizeSynthetic(ctx, ctx.in.gotPlt.get());
2059 finalizeSynthetic(ctx, ctx.in.relaPlt.get());
2060 finalizeSynthetic(ctx, ctx.in.plt.get());
2061 finalizeSynthetic(ctx, ctx.in.iplt.get());
2062 finalizeSynthetic(ctx, ctx.in.ppc32Got2.get());
2063 finalizeSynthetic(ctx, ctx.in.partIndex.get());
2065 // Dynamic section must be the last one in this list and dynamic
2066 // symbol table section (dynSymTab) must be the first one.
2067 for (Partition &part : ctx.partitions) {
2068 if (part.relaDyn) {
2069 part.relaDyn->mergeRels();
2070 // Compute DT_RELACOUNT to be used by part.dynamic.
2071 part.relaDyn->partitionRels();
2072 finalizeSynthetic(ctx, part.relaDyn.get());
2074 if (part.relrDyn) {
2075 part.relrDyn->mergeRels();
2076 finalizeSynthetic(ctx, part.relrDyn.get());
2078 if (part.relrAuthDyn) {
2079 part.relrAuthDyn->mergeRels();
2080 finalizeSynthetic(ctx, part.relrAuthDyn.get());
2083 finalizeSynthetic(ctx, part.dynSymTab.get());
2084 finalizeSynthetic(ctx, part.gnuHashTab.get());
2085 finalizeSynthetic(ctx, part.hashTab.get());
2086 finalizeSynthetic(ctx, part.verDef.get());
2087 finalizeSynthetic(ctx, part.ehFrameHdr.get());
2088 finalizeSynthetic(ctx, part.verSym.get());
2089 finalizeSynthetic(ctx, part.verNeed.get());
2090 finalizeSynthetic(ctx, part.dynamic.get());
2094 if (!ctx.script->hasSectionsCommand && !ctx.arg.relocatable)
2095 fixSectionAlignments();
2097 // This is used to:
2098 // 1) Create "thunks":
2099 // Jump instructions in many ISAs have small displacements, and therefore
2100 // they cannot jump to arbitrary addresses in memory. For example, RISC-V
2101 // JAL instruction can target only +-1 MiB from PC. It is a linker's
2102 // responsibility to create and insert small pieces of code between
2103 // sections to extend the ranges if jump targets are out of range. Such
2104 // code pieces are called "thunks".
2106 // We add thunks at this stage. We couldn't do this before this point
2107 // because this is the earliest point where we know sizes of sections and
2108 // their layouts (that are needed to determine if jump targets are in
2109 // range).
2111 // 2) Update the sections. We need to generate content that depends on the
2112 // address of InputSections. For example, MIPS GOT section content or
2113 // android packed relocations sections content.
2115 // 3) Assign the final values for the linker script symbols. Linker scripts
2116 // sometimes using forward symbol declarations. We want to set the correct
2117 // values. They also might change after adding the thunks.
2118 finalizeAddressDependentContent();
2120 // All information needed for OutputSection part of Map file is available.
2121 if (errCount(ctx))
2122 return;
2125 llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2126 // finalizeAddressDependentContent may have added local symbols to the
2127 // static symbol table.
2128 finalizeSynthetic(ctx, ctx.in.symTab.get());
2129 finalizeSynthetic(ctx, ctx.in.debugNames.get());
2130 finalizeSynthetic(ctx, ctx.in.ppc64LongBranchTarget.get());
2131 finalizeSynthetic(ctx, ctx.in.armCmseSGSection.get());
2134 // Relaxation to delete inter-basic block jumps created by basic block
2135 // sections. Run after ctx.in.symTab is finalized as optimizeBasicBlockJumps
2136 // can relax jump instructions based on symbol offset.
2137 if (ctx.arg.optimizeBBJumps)
2138 optimizeBasicBlockJumps();
2140 // Fill other section headers. The dynamic table is finalized
2141 // at the end because some tags like RELSZ depend on result
2142 // of finalizing other sections.
2143 for (OutputSection *sec : ctx.outputSections)
2144 sec->finalize(ctx);
2146 ctx.script->checkFinalScriptConditions();
2148 if (ctx.arg.emachine == EM_ARM && !ctx.arg.isLE && ctx.arg.armBe8) {
2149 addArmInputSectionMappingSymbols(ctx);
2150 sortArmMappingSymbols(ctx);
2154 // Ensure data sections are not mixed with executable sections when
2155 // --execute-only is used. --execute-only make pages executable but not
2156 // readable.
2157 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2158 if (!ctx.arg.executeOnly)
2159 return;
2161 SmallVector<InputSection *, 0> storage;
2162 for (OutputSection *osec : ctx.outputSections)
2163 if (osec->flags & SHF_EXECINSTR)
2164 for (InputSection *isec : getInputSections(*osec, storage))
2165 if (!(isec->flags & SHF_EXECINSTR))
2166 ErrAlways(ctx) << "cannot place " << isec << " into " << osec->name
2167 << ": --execute-only does not support intermingling "
2168 "data and code";
2171 // The linker is expected to define SECNAME_start and SECNAME_end
2172 // symbols for a few sections. This function defines them.
2173 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2174 // If the associated output section does not exist, there is ambiguity as to
2175 // how we define _start and _end symbols for an init/fini section. Users
2176 // expect no "undefined symbol" linker errors and loaders expect equal
2177 // st_value but do not particularly care whether the symbols are defined or
2178 // not. We retain the output section so that the section indexes will be
2179 // correct.
2180 auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2181 if (os) {
2182 Defined *startSym = addOptionalRegular(ctx, start, os, 0);
2183 Defined *stopSym = addOptionalRegular(ctx, end, os, -1);
2184 if (startSym || stopSym)
2185 os->usedInExpression = true;
2186 } else {
2187 addOptionalRegular(ctx, start, ctx.out.elfHeader.get(), 0);
2188 addOptionalRegular(ctx, end, ctx.out.elfHeader.get(), 0);
2192 define("__preinit_array_start", "__preinit_array_end", ctx.out.preinitArray);
2193 define("__init_array_start", "__init_array_end", ctx.out.initArray);
2194 define("__fini_array_start", "__fini_array_end", ctx.out.finiArray);
2196 // As a special case, don't unnecessarily retain .ARM.exidx, which would
2197 // create an empty PT_ARM_EXIDX.
2198 if (OutputSection *sec = findSection(ctx, ".ARM.exidx"))
2199 define("__exidx_start", "__exidx_end", sec);
2202 // If a section name is valid as a C identifier (which is rare because of
2203 // the leading '.'), linkers are expected to define __start_<secname> and
2204 // __stop_<secname> symbols. They are at beginning and end of the section,
2205 // respectively. This is not requested by the ELF standard, but GNU ld and
2206 // gold provide the feature, and used by many programs.
2207 template <class ELFT>
2208 void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
2209 StringRef s = osec.name;
2210 if (!isValidCIdentifier(s))
2211 return;
2212 StringSaver &ss = ctx.saver;
2213 Defined *startSym = addOptionalRegular(ctx, ss.save("__start_" + s), &osec, 0,
2214 ctx.arg.zStartStopVisibility);
2215 Defined *stopSym = addOptionalRegular(ctx, ss.save("__stop_" + s), &osec, -1,
2216 ctx.arg.zStartStopVisibility);
2217 if (startSym || stopSym)
2218 osec.usedInExpression = true;
2221 static bool needsPtLoad(OutputSection *sec) {
2222 if (!(sec->flags & SHF_ALLOC))
2223 return false;
2225 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2226 // responsible for allocating space for them, not the PT_LOAD that
2227 // contains the TLS initialization image.
2228 if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2229 return false;
2230 return true;
2233 // Adjust phdr flags according to certain options.
2234 static uint64_t computeFlags(Ctx &ctx, uint64_t flags) {
2235 if (ctx.arg.omagic)
2236 return PF_R | PF_W | PF_X;
2237 if (ctx.arg.executeOnly && (flags & PF_X))
2238 return flags & ~PF_R;
2239 return flags;
2242 // Decide which program headers to create and which sections to include in each
2243 // one.
2244 template <class ELFT>
2245 SmallVector<std::unique_ptr<PhdrEntry>, 0>
2246 Writer<ELFT>::createPhdrs(Partition &part) {
2247 SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;
2248 auto addHdr = [&, &ctx = ctx](unsigned type, unsigned flags) -> PhdrEntry * {
2249 ret.push_back(std::make_unique<PhdrEntry>(ctx, type, flags));
2250 return ret.back().get();
2253 unsigned partNo = part.getNumber(ctx);
2254 bool isMain = partNo == 1;
2256 // Add the first PT_LOAD segment for regular output sections.
2257 uint64_t flags = computeFlags(ctx, PF_R);
2258 PhdrEntry *load = nullptr;
2260 // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2261 // PT_LOAD.
2262 if (!ctx.arg.nmagic && !ctx.arg.omagic) {
2263 // The first phdr entry is PT_PHDR which describes the program header
2264 // itself.
2265 if (isMain)
2266 addHdr(PT_PHDR, PF_R)->add(ctx.out.programHeaders.get());
2267 else
2268 addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2270 // PT_INTERP must be the second entry if exists.
2271 if (OutputSection *cmd = findSection(ctx, ".interp", partNo))
2272 addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2274 // Add the headers. We will remove them if they don't fit.
2275 // In the other partitions the headers are ordinary sections, so they don't
2276 // need to be added here.
2277 if (isMain) {
2278 load = addHdr(PT_LOAD, flags);
2279 load->add(ctx.out.elfHeader.get());
2280 load->add(ctx.out.programHeaders.get());
2284 // PT_GNU_RELRO includes all sections that should be marked as
2285 // read-only by dynamic linker after processing relocations.
2286 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2287 // an error message if more than one PT_GNU_RELRO PHDR is required.
2288 auto relRo = std::make_unique<PhdrEntry>(ctx, PT_GNU_RELRO, PF_R);
2289 bool inRelroPhdr = false;
2290 OutputSection *relroEnd = nullptr;
2291 for (OutputSection *sec : ctx.outputSections) {
2292 if (sec->partition != partNo || !needsPtLoad(sec))
2293 continue;
2294 if (isRelroSection(ctx, sec)) {
2295 inRelroPhdr = true;
2296 if (!relroEnd)
2297 relRo->add(sec);
2298 else
2299 ErrAlways(ctx) << "section: " << sec->name
2300 << " is not contiguous with other relro" << " sections";
2301 } else if (inRelroPhdr) {
2302 inRelroPhdr = false;
2303 relroEnd = sec;
2306 relRo->p_align = 1;
2308 for (OutputSection *sec : ctx.outputSections) {
2309 if (!needsPtLoad(sec))
2310 continue;
2312 // Normally, sections in partitions other than the current partition are
2313 // ignored. But partition number 255 is a special case: it contains the
2314 // partition end marker (.part.end). It needs to be added to the main
2315 // partition so that a segment is created for it in the main partition,
2316 // which will cause the dynamic loader to reserve space for the other
2317 // partitions.
2318 if (sec->partition != partNo) {
2319 if (isMain && sec->partition == 255)
2320 addHdr(PT_LOAD, computeFlags(ctx, sec->getPhdrFlags()))->add(sec);
2321 continue;
2324 // Segments are contiguous memory regions that has the same attributes
2325 // (e.g. executable or writable). There is one phdr for each segment.
2326 // Therefore, we need to create a new phdr when the next section has
2327 // incompatible flags or is loaded at a discontiguous address or memory
2328 // region using AT or AT> linker script command, respectively.
2330 // As an exception, we don't create a separate load segment for the ELF
2331 // headers, even if the first "real" output has an AT or AT> attribute.
2333 // In addition, NOBITS sections should only be placed at the end of a LOAD
2334 // segment (since it's represented as p_filesz < p_memsz). If we have a
2335 // not-NOBITS section after a NOBITS, we create a new LOAD for the latter
2336 // even if flags match, so as not to require actually writing the
2337 // supposed-to-be-NOBITS section to the output file. (However, we cannot do
2338 // so when hasSectionsCommand, since we cannot introduce the extra alignment
2339 // needed to create a new LOAD)
2340 uint64_t newFlags = computeFlags(ctx, sec->getPhdrFlags());
2341 // When --no-rosegment is specified, RO and RX sections are compatible.
2342 uint32_t incompatible = flags ^ newFlags;
2343 if (ctx.arg.singleRoRx && !(newFlags & PF_W))
2344 incompatible &= ~PF_X;
2345 if (incompatible)
2346 load = nullptr;
2348 bool sameLMARegion =
2349 load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2350 if (load && sec != relroEnd &&
2351 sec->memRegion == load->firstSec->memRegion &&
2352 (sameLMARegion || load->lastSec == ctx.out.programHeaders.get()) &&
2353 (ctx.script->hasSectionsCommand || sec->type == SHT_NOBITS ||
2354 load->lastSec->type != SHT_NOBITS)) {
2355 load->p_flags |= newFlags;
2356 } else {
2357 load = addHdr(PT_LOAD, newFlags);
2358 flags = newFlags;
2361 load->add(sec);
2364 // Add a TLS segment if any.
2365 auto tlsHdr = std::make_unique<PhdrEntry>(ctx, PT_TLS, PF_R);
2366 for (OutputSection *sec : ctx.outputSections)
2367 if (sec->partition == partNo && sec->flags & SHF_TLS)
2368 tlsHdr->add(sec);
2369 if (tlsHdr->firstSec)
2370 ret.push_back(std::move(tlsHdr));
2372 // Add an entry for .dynamic.
2373 if (OutputSection *sec = part.dynamic->getParent())
2374 addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2376 if (relRo->firstSec)
2377 ret.push_back(std::move(relRo));
2379 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2380 if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2381 part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2382 addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2383 ->add(part.ehFrameHdr->getParent());
2385 if (ctx.arg.osabi == ELFOSABI_OPENBSD) {
2386 // PT_OPENBSD_MUTABLE makes the dynamic linker fill the segment with
2387 // zero data, like bss, but it can be treated differently.
2388 if (OutputSection *cmd = findSection(ctx, ".openbsd.mutable", partNo))
2389 addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
2391 // PT_OPENBSD_RANDOMIZE makes the dynamic linker fill the segment
2392 // with random data.
2393 if (OutputSection *cmd = findSection(ctx, ".openbsd.randomdata", partNo))
2394 addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2396 // PT_OPENBSD_SYSCALLS makes the kernel and dynamic linker register
2397 // system call sites.
2398 if (OutputSection *cmd = findSection(ctx, ".openbsd.syscalls", partNo))
2399 addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
2402 if (ctx.arg.zGnustack != GnuStackKind::None) {
2403 // PT_GNU_STACK is a special section to tell the loader to make the
2404 // pages for the stack non-executable. If you really want an executable
2405 // stack, you can pass -z execstack, but that's not recommended for
2406 // security reasons.
2407 unsigned perm = PF_R | PF_W;
2408 if (ctx.arg.zGnustack == GnuStackKind::Exec)
2409 perm |= PF_X;
2410 addHdr(PT_GNU_STACK, perm)->p_memsz = ctx.arg.zStackSize;
2413 // PT_OPENBSD_NOBTCFI is an OpenBSD-specific header to mark that the
2414 // executable is expected to violate branch-target CFI checks.
2415 if (ctx.arg.zNoBtCfi)
2416 addHdr(PT_OPENBSD_NOBTCFI, PF_X);
2418 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2419 // is expected to perform W^X violations, such as calling mprotect(2) or
2420 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2421 // OpenBSD.
2422 if (ctx.arg.zWxneeded)
2423 addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2425 if (OutputSection *cmd = findSection(ctx, ".note.gnu.property", partNo))
2426 addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2428 // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2429 // same alignment.
2430 PhdrEntry *note = nullptr;
2431 for (OutputSection *sec : ctx.outputSections) {
2432 if (sec->partition != partNo)
2433 continue;
2434 if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2435 if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
2436 note = addHdr(PT_NOTE, PF_R);
2437 note->add(sec);
2438 } else {
2439 note = nullptr;
2442 return ret;
2445 template <class ELFT>
2446 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2447 unsigned pType, unsigned pFlags) {
2448 unsigned partNo = part.getNumber(ctx);
2449 auto i = llvm::find_if(ctx.outputSections, [=](OutputSection *cmd) {
2450 return cmd->partition == partNo && cmd->type == shType;
2452 if (i == ctx.outputSections.end())
2453 return;
2455 auto entry = std::make_unique<PhdrEntry>(ctx, pType, pFlags);
2456 entry->add(*i);
2457 part.phdrs.push_back(std::move(entry));
2460 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2461 // This is achieved by assigning an alignment expression to addrExpr of each
2462 // such section.
2463 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2464 const PhdrEntry *prev;
2465 auto pageAlign = [&, &ctx = this->ctx](const PhdrEntry *p) {
2466 OutputSection *cmd = p->firstSec;
2467 if (!cmd)
2468 return;
2469 cmd->alignExpr = [align = cmd->addralign]() { return align; };
2470 if (!cmd->addrExpr) {
2471 // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2472 // padding in the file contents.
2474 // When -z separate-code is used we must not have any overlap in pages
2475 // between an executable segment and a non-executable segment. We align to
2476 // the next maximum page size boundary on transitions between executable
2477 // and non-executable segments.
2479 // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2480 // sections will be extracted to a separate file. Align to the next
2481 // maximum page size boundary so that we can find the ELF header at the
2482 // start. We cannot benefit from overlapping p_offset ranges with the
2483 // previous segment anyway.
2484 if (ctx.arg.zSeparate == SeparateSegmentKind::Loadable ||
2485 (ctx.arg.zSeparate == SeparateSegmentKind::Code && prev &&
2486 (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2487 cmd->type == SHT_LLVM_PART_EHDR)
2488 cmd->addrExpr = [&ctx = this->ctx] {
2489 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize);
2491 // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2492 // it must be the RW. Align to p_align(PT_TLS) to make sure
2493 // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2494 // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2495 // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2496 // be congruent to 0 modulo p_align(PT_TLS).
2498 // Technically this is not required, but as of 2019, some dynamic loaders
2499 // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2500 // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2501 // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2502 // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2503 // blocks correctly. We need to keep the workaround for a while.
2504 else if (ctx.tlsPhdr && ctx.tlsPhdr->firstSec == p->firstSec)
2505 cmd->addrExpr = [&ctx] {
2506 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2507 alignToPowerOf2(ctx.script->getDot() % ctx.arg.maxPageSize,
2508 ctx.tlsPhdr->p_align);
2510 else
2511 cmd->addrExpr = [&ctx] {
2512 return alignToPowerOf2(ctx.script->getDot(), ctx.arg.maxPageSize) +
2513 ctx.script->getDot() % ctx.arg.maxPageSize;
2518 for (Partition &part : ctx.partitions) {
2519 prev = nullptr;
2520 for (auto &p : part.phdrs)
2521 if (p->p_type == PT_LOAD && p->firstSec) {
2522 pageAlign(p.get());
2523 prev = p.get();
2528 // Compute an in-file position for a given section. The file offset must be the
2529 // same with its virtual address modulo the page size, so that the loader can
2530 // load executables without any address adjustment.
2531 static uint64_t computeFileOffset(Ctx &ctx, OutputSection *os, uint64_t off) {
2532 // The first section in a PT_LOAD has to have congruent offset and address
2533 // modulo the maximum page size.
2534 if (os->ptLoad && os->ptLoad->firstSec == os)
2535 return alignTo(off, os->ptLoad->p_align, os->addr);
2537 // File offsets are not significant for .bss sections other than the first one
2538 // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2539 // increasing rather than setting to zero.
2540 if (os->type == SHT_NOBITS && (!ctx.tlsPhdr || ctx.tlsPhdr->firstSec != os))
2541 return off;
2543 // If the section is not in a PT_LOAD, we just have to align it.
2544 if (!os->ptLoad)
2545 return alignToPowerOf2(off, os->addralign);
2547 // If two sections share the same PT_LOAD the file offset is calculated
2548 // using this formula: Off2 = Off1 + (VA2 - VA1).
2549 OutputSection *first = os->ptLoad->firstSec;
2550 return first->offset + os->addr - first->addr;
2553 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2554 // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2555 auto needsOffset = [](OutputSection &sec) {
2556 return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2558 uint64_t minAddr = UINT64_MAX;
2559 for (OutputSection *sec : ctx.outputSections)
2560 if (needsOffset(*sec)) {
2561 sec->offset = sec->getLMA();
2562 minAddr = std::min(minAddr, sec->offset);
2565 // Sections are laid out at LMA minus minAddr.
2566 fileSize = 0;
2567 for (OutputSection *sec : ctx.outputSections)
2568 if (needsOffset(*sec)) {
2569 sec->offset -= minAddr;
2570 fileSize = std::max(fileSize, sec->offset + sec->size);
2574 static std::string rangeToString(uint64_t addr, uint64_t len) {
2575 return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2578 // Assign file offsets to output sections.
2579 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2580 ctx.out.programHeaders->offset = ctx.out.elfHeader->size;
2581 uint64_t off = ctx.out.elfHeader->size + ctx.out.programHeaders->size;
2583 PhdrEntry *lastRX = nullptr;
2584 for (Partition &part : ctx.partitions)
2585 for (auto &p : part.phdrs)
2586 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2587 lastRX = p.get();
2589 // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2590 // will not occupy file offsets contained by a PT_LOAD.
2591 for (OutputSection *sec : ctx.outputSections) {
2592 if (!(sec->flags & SHF_ALLOC))
2593 continue;
2594 off = computeFileOffset(ctx, sec, off);
2595 sec->offset = off;
2596 if (sec->type != SHT_NOBITS)
2597 off += sec->size;
2599 // If this is a last section of the last executable segment and that
2600 // segment is the last loadable segment, align the offset of the
2601 // following section to avoid loading non-segments parts of the file.
2602 if (ctx.arg.zSeparate != SeparateSegmentKind::None && lastRX &&
2603 lastRX->lastSec == sec)
2604 off = alignToPowerOf2(off, ctx.arg.maxPageSize);
2606 for (OutputSection *osec : ctx.outputSections) {
2607 if (osec->flags & SHF_ALLOC)
2608 continue;
2609 osec->offset = alignToPowerOf2(off, osec->addralign);
2610 off = osec->offset + osec->size;
2613 sectionHeaderOff = alignToPowerOf2(off, ctx.arg.wordsize);
2614 fileSize =
2615 sectionHeaderOff + (ctx.outputSections.size() + 1) * sizeof(Elf_Shdr);
2617 // Our logic assumes that sections have rising VA within the same segment.
2618 // With use of linker scripts it is possible to violate this rule and get file
2619 // offset overlaps or overflows. That should never happen with a valid script
2620 // which does not move the location counter backwards and usually scripts do
2621 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2622 // kernel, which control segment distribution explicitly and move the counter
2623 // backwards, so we have to allow doing that to support linking them. We
2624 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2625 // we want to prevent file size overflows because it would crash the linker.
2626 for (OutputSection *sec : ctx.outputSections) {
2627 if (sec->type == SHT_NOBITS)
2628 continue;
2629 if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2630 ErrAlways(ctx) << "unable to place section " << sec->name
2631 << " at file offset "
2632 << rangeToString(sec->offset, sec->size)
2633 << "; check your linker script for overflows";
2637 // Finalize the program headers. We call this function after we assign
2638 // file offsets and VAs to all sections.
2639 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2640 for (std::unique_ptr<PhdrEntry> &p : part.phdrs) {
2641 OutputSection *first = p->firstSec;
2642 OutputSection *last = p->lastSec;
2644 // .ARM.exidx sections may not be within a single .ARM.exidx
2645 // output section. We always want to describe just the
2646 // SyntheticSection.
2647 if (part.armExidx && p->p_type == PT_ARM_EXIDX) {
2648 p->p_filesz = part.armExidx->getSize();
2649 p->p_memsz = p->p_filesz;
2650 p->p_offset = first->offset + part.armExidx->outSecOff;
2651 p->p_vaddr = first->addr + part.armExidx->outSecOff;
2652 p->p_align = part.armExidx->addralign;
2653 if (part.elfHeader)
2654 p->p_offset -= part.elfHeader->getParent()->offset;
2656 if (!p->hasLMA)
2657 p->p_paddr = first->getLMA() + part.armExidx->outSecOff;
2658 return;
2661 if (first) {
2662 p->p_filesz = last->offset - first->offset;
2663 if (last->type != SHT_NOBITS)
2664 p->p_filesz += last->size;
2666 p->p_memsz = last->addr + last->size - first->addr;
2667 p->p_offset = first->offset;
2668 p->p_vaddr = first->addr;
2670 // File offsets in partitions other than the main partition are relative
2671 // to the offset of the ELF headers. Perform that adjustment now.
2672 if (part.elfHeader)
2673 p->p_offset -= part.elfHeader->getParent()->offset;
2675 if (!p->hasLMA)
2676 p->p_paddr = first->getLMA();
2681 // A helper struct for checkSectionOverlap.
2682 namespace {
2683 struct SectionOffset {
2684 OutputSection *sec;
2685 uint64_t offset;
2687 } // namespace
2689 // Check whether sections overlap for a specific address range (file offsets,
2690 // load and virtual addresses).
2691 static void checkOverlap(Ctx &ctx, StringRef name,
2692 std::vector<SectionOffset> &sections,
2693 bool isVirtualAddr) {
2694 llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2695 return a.offset < b.offset;
2698 // Finding overlap is easy given a vector is sorted by start position.
2699 // If an element starts before the end of the previous element, they overlap.
2700 for (size_t i = 1, end = sections.size(); i < end; ++i) {
2701 SectionOffset a = sections[i - 1];
2702 SectionOffset b = sections[i];
2703 if (b.offset >= a.offset + a.sec->size)
2704 continue;
2706 // If both sections are in OVERLAY we allow the overlapping of virtual
2707 // addresses, because it is what OVERLAY was designed for.
2708 if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2709 continue;
2711 Err(ctx) << "section " << a.sec->name << " " << name
2712 << " range overlaps with " << b.sec->name << "\n>>> "
2713 << a.sec->name << " range is "
2714 << rangeToString(a.offset, a.sec->size) << "\n>>> " << b.sec->name
2715 << " range is " << rangeToString(b.offset, b.sec->size);
2719 // Check for overlapping sections and address overflows.
2721 // In this function we check that none of the output sections have overlapping
2722 // file offsets. For SHF_ALLOC sections we also check that the load address
2723 // ranges and the virtual address ranges don't overlap
2724 template <class ELFT> void Writer<ELFT>::checkSections() {
2725 // First, check that section's VAs fit in available address space for target.
2726 for (OutputSection *os : ctx.outputSections)
2727 if ((os->addr + os->size < os->addr) ||
2728 (!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
2729 Err(ctx) << "section " << os->name << " at 0x"
2730 << utohexstr(os->addr, true) << " of size 0x"
2731 << utohexstr(os->size, true)
2732 << " exceeds available address space";
2734 // Check for overlapping file offsets. In this case we need to skip any
2735 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2736 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2737 // binary is specified only add SHF_ALLOC sections are added to the output
2738 // file so we skip any non-allocated sections in that case.
2739 std::vector<SectionOffset> fileOffs;
2740 for (OutputSection *sec : ctx.outputSections)
2741 if (sec->size > 0 && sec->type != SHT_NOBITS &&
2742 (!ctx.arg.oFormatBinary || (sec->flags & SHF_ALLOC)))
2743 fileOffs.push_back({sec, sec->offset});
2744 checkOverlap(ctx, "file", fileOffs, false);
2746 // When linking with -r there is no need to check for overlapping virtual/load
2747 // addresses since those addresses will only be assigned when the final
2748 // executable/shared object is created.
2749 if (ctx.arg.relocatable)
2750 return;
2752 // Checking for overlapping virtual and load addresses only needs to take
2753 // into account SHF_ALLOC sections since others will not be loaded.
2754 // Furthermore, we also need to skip SHF_TLS sections since these will be
2755 // mapped to other addresses at runtime and can therefore have overlapping
2756 // ranges in the file.
2757 std::vector<SectionOffset> vmas;
2758 for (OutputSection *sec : ctx.outputSections)
2759 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2760 vmas.push_back({sec, sec->addr});
2761 checkOverlap(ctx, "virtual address", vmas, true);
2763 // Finally, check that the load addresses don't overlap. This will usually be
2764 // the same as the virtual addresses but can be different when using a linker
2765 // script with AT().
2766 std::vector<SectionOffset> lmas;
2767 for (OutputSection *sec : ctx.outputSections)
2768 if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2769 lmas.push_back({sec, sec->getLMA()});
2770 checkOverlap(ctx, "load address", lmas, false);
2773 // The entry point address is chosen in the following ways.
2775 // 1. the '-e' entry command-line option;
2776 // 2. the ENTRY(symbol) command in a linker control script;
2777 // 3. the value of the symbol _start, if present;
2778 // 4. the number represented by the entry symbol, if it is a number;
2779 // 5. the address 0.
2780 static uint64_t getEntryAddr(Ctx &ctx) {
2781 // Case 1, 2 or 3
2782 if (Symbol *b = ctx.symtab->find(ctx.arg.entry))
2783 return b->getVA(ctx);
2785 // Case 4
2786 uint64_t addr;
2787 if (to_integer(ctx.arg.entry, addr))
2788 return addr;
2790 // Case 5
2791 if (ctx.arg.warnMissingEntry)
2792 Warn(ctx) << "cannot find entry symbol " << ctx.arg.entry
2793 << "; not setting start address";
2794 return 0;
2797 static uint16_t getELFType(Ctx &ctx) {
2798 if (ctx.arg.isPic)
2799 return ET_DYN;
2800 if (ctx.arg.relocatable)
2801 return ET_REL;
2802 return ET_EXEC;
2805 template <class ELFT> void Writer<ELFT>::writeHeader() {
2806 writeEhdr<ELFT>(ctx, ctx.bufferStart, *ctx.mainPart);
2807 writePhdrs<ELFT>(ctx.bufferStart + sizeof(Elf_Ehdr), *ctx.mainPart);
2809 auto *eHdr = reinterpret_cast<Elf_Ehdr *>(ctx.bufferStart);
2810 eHdr->e_type = getELFType(ctx);
2811 eHdr->e_entry = getEntryAddr(ctx);
2813 // If -z nosectionheader is specified, omit the section header table.
2814 if (!ctx.in.shStrTab)
2815 return;
2816 eHdr->e_shoff = sectionHeaderOff;
2818 // Write the section header table.
2820 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2821 // and e_shstrndx fields. When the value of one of these fields exceeds
2822 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2823 // use fields in the section header at index 0 to store
2824 // the value. The sentinel values and fields are:
2825 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2826 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2827 auto *sHdrs = reinterpret_cast<Elf_Shdr *>(ctx.bufferStart + eHdr->e_shoff);
2828 size_t num = ctx.outputSections.size() + 1;
2829 if (num >= SHN_LORESERVE)
2830 sHdrs->sh_size = num;
2831 else
2832 eHdr->e_shnum = num;
2834 uint32_t strTabIndex = ctx.in.shStrTab->getParent()->sectionIndex;
2835 if (strTabIndex >= SHN_LORESERVE) {
2836 sHdrs->sh_link = strTabIndex;
2837 eHdr->e_shstrndx = SHN_XINDEX;
2838 } else {
2839 eHdr->e_shstrndx = strTabIndex;
2842 for (OutputSection *sec : ctx.outputSections)
2843 sec->writeHeaderTo<ELFT>(++sHdrs);
2846 // Open a result file.
2847 template <class ELFT> void Writer<ELFT>::openFile() {
2848 uint64_t maxSize = ctx.arg.is64 ? INT64_MAX : UINT32_MAX;
2849 if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2850 std::string msg;
2851 raw_string_ostream s(msg);
2852 s << "output file too large: " << fileSize << " bytes\n"
2853 << "section sizes:\n";
2854 for (OutputSection *os : ctx.outputSections)
2855 s << os->name << ' ' << os->size << "\n";
2856 ErrAlways(ctx) << msg;
2857 return;
2860 unlinkAsync(ctx.arg.outputFile);
2861 unsigned flags = 0;
2862 if (!ctx.arg.relocatable)
2863 flags |= FileOutputBuffer::F_executable;
2864 if (!ctx.arg.mmapOutputFile)
2865 flags |= FileOutputBuffer::F_no_mmap;
2866 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2867 FileOutputBuffer::create(ctx.arg.outputFile, fileSize, flags);
2869 if (!bufferOrErr) {
2870 ErrAlways(ctx) << "failed to open " << ctx.arg.outputFile << ": "
2871 << bufferOrErr.takeError();
2872 return;
2874 buffer = std::move(*bufferOrErr);
2875 ctx.bufferStart = buffer->getBufferStart();
2878 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2879 parallel::TaskGroup tg;
2880 for (OutputSection *sec : ctx.outputSections)
2881 if (sec->flags & SHF_ALLOC)
2882 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2885 static void fillTrap(std::array<uint8_t, 4> trapInstr, uint8_t *i,
2886 uint8_t *end) {
2887 for (; i + 4 <= end; i += 4)
2888 memcpy(i, trapInstr.data(), 4);
2891 // Fill the last page of executable segments with trap instructions
2892 // instead of leaving them as zero. Even though it is not required by any
2893 // standard, it is in general a good thing to do for security reasons.
2895 // We'll leave other pages in segments as-is because the rest will be
2896 // overwritten by output sections.
2897 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2898 for (Partition &part : ctx.partitions) {
2899 // Fill the last page.
2900 for (std::unique_ptr<PhdrEntry> &p : part.phdrs)
2901 if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2902 fillTrap(
2903 ctx.target->trapInstr,
2904 ctx.bufferStart + alignDown(p->firstSec->offset + p->p_filesz, 4),
2905 ctx.bufferStart + alignToPowerOf2(p->firstSec->offset + p->p_filesz,
2906 ctx.arg.maxPageSize));
2908 // Round up the file size of the last segment to the page boundary iff it is
2909 // an executable segment to ensure that other tools don't accidentally
2910 // trim the instruction padding (e.g. when stripping the file).
2911 PhdrEntry *last = nullptr;
2912 for (std::unique_ptr<PhdrEntry> &p : part.phdrs)
2913 if (p->p_type == PT_LOAD)
2914 last = p.get();
2916 if (last && (last->p_flags & PF_X))
2917 last->p_memsz = last->p_filesz =
2918 alignToPowerOf2(last->p_filesz, ctx.arg.maxPageSize);
2922 // Write section contents to a mmap'ed file.
2923 template <class ELFT> void Writer<ELFT>::writeSections() {
2924 llvm::TimeTraceScope timeScope("Write sections");
2927 // In -r or --emit-relocs mode, write the relocation sections first as in
2928 // ELf_Rel targets we might find out that we need to modify the relocated
2929 // section while doing it.
2930 parallel::TaskGroup tg;
2931 for (OutputSection *sec : ctx.outputSections)
2932 if (isStaticRelSecType(sec->type))
2933 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2936 parallel::TaskGroup tg;
2937 for (OutputSection *sec : ctx.outputSections)
2938 if (!isStaticRelSecType(sec->type))
2939 sec->writeTo<ELFT>(ctx, ctx.bufferStart + sec->offset, tg);
2942 // Finally, check that all dynamic relocation addends were written correctly.
2943 if (ctx.arg.checkDynamicRelocs && ctx.arg.writeAddends) {
2944 for (OutputSection *sec : ctx.outputSections)
2945 if (isStaticRelSecType(sec->type))
2946 sec->checkDynRelAddends(ctx);
2950 // Computes a hash value of Data using a given hash function.
2951 // In order to utilize multiple cores, we first split data into 1MB
2952 // chunks, compute a hash for each chunk, and then compute a hash value
2953 // of the hash values.
2954 static void
2955 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2956 llvm::ArrayRef<uint8_t> data,
2957 std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2958 std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2959 const size_t hashesSize = chunks.size() * hashBuf.size();
2960 std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2962 // Compute hash values.
2963 parallelFor(0, chunks.size(), [&](size_t i) {
2964 hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2967 // Write to the final output buffer.
2968 hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
2971 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2972 if (!ctx.mainPart->buildId || !ctx.mainPart->buildId->getParent())
2973 return;
2975 if (ctx.arg.buildId == BuildIdKind::Hexstring) {
2976 for (Partition &part : ctx.partitions)
2977 part.buildId->writeBuildId(ctx.arg.buildIdVector);
2978 return;
2981 // Compute a hash of all sections of the output file.
2982 size_t hashSize = ctx.mainPart->buildId->hashSize;
2983 std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2984 MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2985 llvm::ArrayRef<uint8_t> input{ctx.bufferStart, size_t(fileSize)};
2987 // Fedora introduced build ID as "approximation of true uniqueness across all
2988 // binaries that might be used by overlapping sets of people". It does not
2989 // need some security goals that some hash algorithms strive to provide, e.g.
2990 // (second-)preimage and collision resistance. In practice people use 'md5'
2991 // and 'sha1' just for different lengths. Implement them with the more
2992 // efficient BLAKE3.
2993 switch (ctx.arg.buildId) {
2994 case BuildIdKind::Fast:
2995 computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2996 write64le(dest, xxh3_64bits(arr));
2998 break;
2999 case BuildIdKind::Md5:
3000 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3001 memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
3003 break;
3004 case BuildIdKind::Sha1:
3005 computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3006 memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
3008 break;
3009 case BuildIdKind::Uuid:
3010 if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
3011 ErrAlways(ctx) << "entropy source failure: " << ec.message();
3012 break;
3013 default:
3014 llvm_unreachable("unknown BuildIdKind");
3016 for (Partition &part : ctx.partitions)
3017 part.buildId->writeBuildId(output);
3020 template void elf::writeResult<ELF32LE>(Ctx &);
3021 template void elf::writeResult<ELF32BE>(Ctx &);
3022 template void elf::writeResult<ELF64LE>(Ctx &);
3023 template void elf::writeResult<ELF64BE>(Ctx &);