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