xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision a75a46db)
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 //===----------------------------------------------------------------------===//
8 
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/StringMap.h"
28 #include "llvm/Support/BLAKE3.h"
29 #include "llvm/Support/Parallel.h"
30 #include "llvm/Support/RandomNumberGenerator.h"
31 #include "llvm/Support/TimeProfiler.h"
32 #include "llvm/Support/xxhash.h"
33 #include <climits>
34 
35 #define DEBUG_TYPE "lld"
36 
37 using namespace llvm;
38 using namespace llvm::ELF;
39 using namespace llvm::object;
40 using namespace llvm::support;
41 using namespace llvm::support::endian;
42 using namespace lld;
43 using namespace lld::elf;
44 
45 namespace {
46 // The writer writes a SymbolTable result to a file.
47 template <class ELFT> class Writer {
48 public:
49   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
50 
51   Writer() : buffer(errorHandler().outputBuffer) {}
52 
53   void run();
54 
55 private:
56   void copyLocalSymbols();
57   void addSectionSymbols();
58   void sortSections();
59   void resolveShfLinkOrder();
60   void finalizeAddressDependentContent();
61   void optimizeBasicBlockJumps();
62   void sortInputSections();
63   void finalizeSections();
64   void checkExecuteOnly();
65   void setReservedSymbolSections();
66 
67   SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);
68   void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
69                          unsigned pFlags);
70   void assignFileOffsets();
71   void assignFileOffsetsBinary();
72   void setPhdrs(Partition &part);
73   void checkSections();
74   void fixSectionAlignments();
75   void openFile();
76   void writeTrapInstr();
77   void writeHeader();
78   void writeSections();
79   void writeSectionsBinary();
80   void writeBuildId();
81 
82   std::unique_ptr<FileOutputBuffer> &buffer;
83 
84   void addRelIpltSymbols();
85   void addStartEndSymbols();
86   void addStartStopSymbols(OutputSection &osec);
87 
88   uint64_t fileSize;
89   uint64_t sectionHeaderOff;
90 };
91 } // anonymous namespace
92 
93 static bool needsInterpSection() {
94   return !config->relocatable && !config->shared &&
95          !config->dynamicLinker.empty() && script->needsInterpSection();
96 }
97 
98 template <class ELFT> void elf::writeResult() {
99   Writer<ELFT>().run();
100 }
101 
102 static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {
103   auto it = std::stable_partition(
104       phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
105         if (p->p_type != PT_LOAD)
106           return true;
107         if (!p->firstSec)
108           return false;
109         uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
110         return size != 0;
111       });
112 
113   // Clear OutputSection::ptLoad for sections contained in removed
114   // segments.
115   DenseSet<PhdrEntry *> removed(it, phdrs.end());
116   for (OutputSection *sec : outputSections)
117     if (removed.count(sec->ptLoad))
118       sec->ptLoad = nullptr;
119   phdrs.erase(it, phdrs.end());
120 }
121 
122 void elf::copySectionsIntoPartitions() {
123   SmallVector<InputSectionBase *, 0> newSections;
124   for (unsigned part = 2; part != partitions.size() + 1; ++part) {
125     for (InputSectionBase *s : inputSections) {
126       if (!(s->flags & SHF_ALLOC) || !s->isLive())
127         continue;
128       InputSectionBase *copy;
129       if (s->type == SHT_NOTE)
130         copy = make<InputSection>(cast<InputSection>(*s));
131       else if (auto *es = dyn_cast<EhInputSection>(s))
132         copy = make<EhInputSection>(*es);
133       else
134         continue;
135       copy->partition = part;
136       newSections.push_back(copy);
137     }
138   }
139 
140   inputSections.insert(inputSections.end(), newSections.begin(),
141                        newSections.end());
142 }
143 
144 void elf::combineEhSections() {
145   llvm::TimeTraceScope timeScope("Combine EH sections");
146   for (InputSectionBase *&s : inputSections) {
147     // Ignore dead sections and the partition end marker (.part.end),
148     // whose partition number is out of bounds.
149     if (!s->isLive() || s->partition == 255)
150       continue;
151 
152     Partition &part = s->getPartition();
153     if (auto *es = dyn_cast<EhInputSection>(s)) {
154       part.ehFrame->addSection(es);
155       s = nullptr;
156     } else if (s->kind() == SectionBase::Regular && part.armExidx &&
157                part.armExidx->addSection(cast<InputSection>(s))) {
158       s = nullptr;
159     }
160   }
161 
162   llvm::erase_value(inputSections, nullptr);
163 }
164 
165 static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
166                                    uint64_t val, uint8_t stOther = STV_HIDDEN) {
167   Symbol *s = symtab->find(name);
168   if (!s || s->isDefined() || s->isCommon())
169     return nullptr;
170 
171   s->resolve(Defined{nullptr, StringRef(), STB_GLOBAL, stOther, STT_NOTYPE, val,
172                      /*size=*/0, sec});
173   s->isUsedInRegularObj = true;
174   return cast<Defined>(s);
175 }
176 
177 static Defined *addAbsolute(StringRef name) {
178   Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN,
179                                           STT_NOTYPE, 0, 0, nullptr});
180   sym->isUsedInRegularObj = true;
181   return cast<Defined>(sym);
182 }
183 
184 // The linker is expected to define some symbols depending on
185 // the linking result. This function defines such symbols.
186 void elf::addReservedSymbols() {
187   if (config->emachine == EM_MIPS) {
188     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
189     // so that it points to an absolute address which by default is relative
190     // to GOT. Default offset is 0x7ff0.
191     // See "Global Data Symbols" in Chapter 6 in the following document:
192     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
193     ElfSym::mipsGp = addAbsolute("_gp");
194 
195     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
196     // start of function and 'gp' pointer into GOT.
197     if (symtab->find("_gp_disp"))
198       ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
199 
200     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
201     // pointer. This symbol is used in the code generated by .cpload pseudo-op
202     // in case of using -mno-shared option.
203     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
204     if (symtab->find("__gnu_local_gp"))
205       ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
206   } else if (config->emachine == EM_PPC) {
207     // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't
208     // support Small Data Area, define it arbitrarily as 0.
209     addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
210   } else if (config->emachine == EM_PPC64) {
211     addPPC64SaveRestore();
212   }
213 
214   // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
215   // combines the typical ELF GOT with the small data sections. It commonly
216   // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
217   // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
218   // represent the TOC base which is offset by 0x8000 bytes from the start of
219   // the .got section.
220   // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
221   // correctness of some relocations depends on its value.
222   StringRef gotSymName =
223       (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
224 
225   if (Symbol *s = symtab->find(gotSymName)) {
226     if (s->isDefined()) {
227       error(toString(s->file) + " cannot redefine linker defined symbol '" +
228             gotSymName + "'");
229       return;
230     }
231 
232     uint64_t gotOff = 0;
233     if (config->emachine == EM_PPC64)
234       gotOff = 0x8000;
235 
236     s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
237                        STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader});
238     ElfSym::globalOffsetTable = cast<Defined>(s);
239   }
240 
241   // __ehdr_start is the location of ELF file headers. Note that we define
242   // this symbol unconditionally even when using a linker script, which
243   // differs from the behavior implemented by GNU linker which only define
244   // this symbol if ELF headers are in the memory mapped segment.
245   addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
246 
247   // __executable_start is not documented, but the expectation of at
248   // least the Android libc is that it points to the ELF header.
249   addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
250 
251   // __dso_handle symbol is passed to cxa_finalize as a marker to identify
252   // each DSO. The address of the symbol doesn't matter as long as they are
253   // different in different DSOs, so we chose the start address of the DSO.
254   addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
255 
256   // If linker script do layout we do not need to create any standard symbols.
257   if (script->hasSectionsCommand)
258     return;
259 
260   auto add = [](StringRef s, int64_t pos) {
261     return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
262   };
263 
264   ElfSym::bss = add("__bss_start", 0);
265   ElfSym::end1 = add("end", -1);
266   ElfSym::end2 = add("_end", -1);
267   ElfSym::etext1 = add("etext", -1);
268   ElfSym::etext2 = add("_etext", -1);
269   ElfSym::edata1 = add("edata", -1);
270   ElfSym::edata2 = add("_edata", -1);
271 }
272 
273 static OutputSection *findSection(StringRef name, unsigned partition = 1) {
274   for (SectionCommand *cmd : script->sectionCommands)
275     if (auto *osd = dyn_cast<OutputDesc>(cmd))
276       if (osd->osec.name == name && osd->osec.partition == partition)
277         return &osd->osec;
278   return nullptr;
279 }
280 
281 template <class ELFT> void elf::createSyntheticSections() {
282   // Initialize all pointers with NULL. This is needed because
283   // you can call lld::elf::main more than once as a library.
284   Out::tlsPhdr = nullptr;
285   Out::preinitArray = nullptr;
286   Out::initArray = nullptr;
287   Out::finiArray = nullptr;
288 
289   // Add the .interp section first because it is not a SyntheticSection.
290   // The removeUnusedSyntheticSections() function relies on the
291   // SyntheticSections coming last.
292   if (needsInterpSection()) {
293     for (size_t i = 1; i <= partitions.size(); ++i) {
294       InputSection *sec = createInterpSection();
295       sec->partition = i;
296       inputSections.push_back(sec);
297     }
298   }
299 
300   auto add = [](SyntheticSection &sec) { inputSections.push_back(&sec); };
301 
302   in.shStrTab = std::make_unique<StringTableSection>(".shstrtab", false);
303 
304   Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC);
305   Out::programHeaders->alignment = config->wordsize;
306 
307   if (config->strip != StripPolicy::All) {
308     in.strTab = std::make_unique<StringTableSection>(".strtab", false);
309     in.symTab = std::make_unique<SymbolTableSection<ELFT>>(*in.strTab);
310     in.symTabShndx = std::make_unique<SymtabShndxSection>();
311   }
312 
313   in.bss = std::make_unique<BssSection>(".bss", 0, 1);
314   add(*in.bss);
315 
316   // If there is a SECTIONS command and a .data.rel.ro section name use name
317   // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
318   // This makes sure our relro is contiguous.
319   bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro");
320   in.bssRelRo = std::make_unique<BssSection>(
321       hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
322   add(*in.bssRelRo);
323 
324   // Add MIPS-specific sections.
325   if (config->emachine == EM_MIPS) {
326     if (!config->shared && config->hasDynSymTab) {
327       in.mipsRldMap = std::make_unique<MipsRldMapSection>();
328       add(*in.mipsRldMap);
329     }
330     if ((in.mipsAbiFlags = MipsAbiFlagsSection<ELFT>::create()))
331       add(*in.mipsAbiFlags);
332     if ((in.mipsOptions = MipsOptionsSection<ELFT>::create()))
333       add(*in.mipsOptions);
334     if ((in.mipsReginfo = MipsReginfoSection<ELFT>::create()))
335       add(*in.mipsReginfo);
336   }
337 
338   StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn";
339 
340   for (Partition &part : partitions) {
341     auto add = [&](SyntheticSection &sec) {
342       sec.partition = part.getNumber();
343       inputSections.push_back(&sec);
344     };
345 
346     if (!part.name.empty()) {
347       part.elfHeader = std::make_unique<PartitionElfHeaderSection<ELFT>>();
348       part.elfHeader->name = part.name;
349       add(*part.elfHeader);
350 
351       part.programHeaders =
352           std::make_unique<PartitionProgramHeadersSection<ELFT>>();
353       add(*part.programHeaders);
354     }
355 
356     if (config->buildId != BuildIdKind::None) {
357       part.buildId = std::make_unique<BuildIdSection>();
358       add(*part.buildId);
359     }
360 
361     part.dynStrTab = std::make_unique<StringTableSection>(".dynstr", true);
362     part.dynSymTab =
363         std::make_unique<SymbolTableSection<ELFT>>(*part.dynStrTab);
364     part.dynamic = std::make_unique<DynamicSection<ELFT>>();
365     if (config->androidPackDynRelocs)
366       part.relaDyn =
367           std::make_unique<AndroidPackedRelocationSection<ELFT>>(relaDynName);
368     else
369       part.relaDyn = std::make_unique<RelocationSection<ELFT>>(
370           relaDynName, config->zCombreloc);
371 
372     if (config->hasDynSymTab) {
373       add(*part.dynSymTab);
374 
375       part.verSym = std::make_unique<VersionTableSection>();
376       add(*part.verSym);
377 
378       if (!namedVersionDefs().empty()) {
379         part.verDef = std::make_unique<VersionDefinitionSection>();
380         add(*part.verDef);
381       }
382 
383       part.verNeed = std::make_unique<VersionNeedSection<ELFT>>();
384       add(*part.verNeed);
385 
386       if (config->gnuHash) {
387         part.gnuHashTab = std::make_unique<GnuHashTableSection>();
388         add(*part.gnuHashTab);
389       }
390 
391       if (config->sysvHash) {
392         part.hashTab = std::make_unique<HashTableSection>();
393         add(*part.hashTab);
394       }
395 
396       add(*part.dynamic);
397       add(*part.dynStrTab);
398       add(*part.relaDyn);
399     }
400 
401     if (config->relrPackDynRelocs) {
402       part.relrDyn = std::make_unique<RelrSection<ELFT>>();
403       add(*part.relrDyn);
404     }
405 
406     if (!config->relocatable) {
407       if (config->ehFrameHdr) {
408         part.ehFrameHdr = std::make_unique<EhFrameHeader>();
409         add(*part.ehFrameHdr);
410       }
411       part.ehFrame = std::make_unique<EhFrameSection>();
412       add(*part.ehFrame);
413     }
414 
415     if (config->emachine == EM_ARM && !config->relocatable) {
416       // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx
417       // InputSections.
418       part.armExidx = std::make_unique<ARMExidxSyntheticSection>();
419       add(*part.armExidx);
420     }
421   }
422 
423   if (partitions.size() != 1) {
424     // Create the partition end marker. This needs to be in partition number 255
425     // so that it is sorted after all other partitions. It also has other
426     // special handling (see createPhdrs() and combineEhSections()).
427     in.partEnd =
428         std::make_unique<BssSection>(".part.end", config->maxPageSize, 1);
429     in.partEnd->partition = 255;
430     add(*in.partEnd);
431 
432     in.partIndex = std::make_unique<PartitionIndexSection>();
433     addOptionalRegular("__part_index_begin", in.partIndex.get(), 0);
434     addOptionalRegular("__part_index_end", in.partIndex.get(),
435                        in.partIndex->getSize());
436     add(*in.partIndex);
437   }
438 
439   // Add .got. MIPS' .got is so different from the other archs,
440   // it has its own class.
441   if (config->emachine == EM_MIPS) {
442     in.mipsGot = std::make_unique<MipsGotSection>();
443     add(*in.mipsGot);
444   } else {
445     in.got = std::make_unique<GotSection>();
446     add(*in.got);
447   }
448 
449   if (config->emachine == EM_PPC) {
450     in.ppc32Got2 = std::make_unique<PPC32Got2Section>();
451     add(*in.ppc32Got2);
452   }
453 
454   if (config->emachine == EM_PPC64) {
455     in.ppc64LongBranchTarget = std::make_unique<PPC64LongBranchTargetSection>();
456     add(*in.ppc64LongBranchTarget);
457   }
458 
459   in.gotPlt = std::make_unique<GotPltSection>();
460   add(*in.gotPlt);
461   in.igotPlt = std::make_unique<IgotPltSection>();
462   add(*in.igotPlt);
463 
464   // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat
465   // it as a relocation and ensure the referenced section is created.
466   if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) {
467     if (target->gotBaseSymInGotPlt)
468       in.gotPlt->hasGotPltOffRel = true;
469     else
470       in.got->hasGotOffRel = true;
471   }
472 
473   if (config->gdbIndex)
474     add(*GdbIndexSection::create<ELFT>());
475 
476   // We always need to add rel[a].plt to output if it has entries.
477   // Even for static linking it can contain R_[*]_IRELATIVE relocations.
478   in.relaPlt = std::make_unique<RelocationSection<ELFT>>(
479       config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false);
480   add(*in.relaPlt);
481 
482   // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative
483   // relocations are processed last by the dynamic loader. We cannot place the
484   // iplt section in .rel.dyn when Android relocation packing is enabled because
485   // that would cause a section type mismatch. However, because the Android
486   // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired
487   // behaviour by placing the iplt section in .rel.plt.
488   in.relaIplt = std::make_unique<RelocationSection<ELFT>>(
489       config->androidPackDynRelocs ? in.relaPlt->name : relaDynName,
490       /*sort=*/false);
491   add(*in.relaIplt);
492 
493   if ((config->emachine == EM_386 || config->emachine == EM_X86_64) &&
494       (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
495     in.ibtPlt = std::make_unique<IBTPltSection>();
496     add(*in.ibtPlt);
497   }
498 
499   if (config->emachine == EM_PPC)
500     in.plt = std::make_unique<PPC32GlinkSection>();
501   else
502     in.plt = std::make_unique<PltSection>();
503   add(*in.plt);
504   in.iplt = std::make_unique<IpltSection>();
505   add(*in.iplt);
506 
507   if (config->andFeatures)
508     add(*make<GnuPropertySection>());
509 
510   // .note.GNU-stack is always added when we are creating a re-linkable
511   // object file. Other linkers are using the presence of this marker
512   // section to control the executable-ness of the stack area, but that
513   // is irrelevant these days. Stack area should always be non-executable
514   // by default. So we emit this section unconditionally.
515   if (config->relocatable)
516     add(*make<GnuStackSection>());
517 
518   if (in.symTab)
519     add(*in.symTab);
520   if (in.symTabShndx)
521     add(*in.symTabShndx);
522   add(*in.shStrTab);
523   if (in.strTab)
524     add(*in.strTab);
525 }
526 
527 // The main function of the writer.
528 template <class ELFT> void Writer<ELFT>::run() {
529   copyLocalSymbols();
530 
531   if (config->copyRelocs)
532     addSectionSymbols();
533 
534   // Now that we have a complete set of output sections. This function
535   // completes section contents. For example, we need to add strings
536   // to the string table, and add entries to .got and .plt.
537   // finalizeSections does that.
538   finalizeSections();
539   checkExecuteOnly();
540 
541   // If --compressed-debug-sections is specified, compress .debug_* sections.
542   // Do it right now because it changes the size of output sections.
543   for (OutputSection *sec : outputSections)
544     sec->maybeCompress<ELFT>();
545 
546   if (script->hasSectionsCommand)
547     script->allocateHeaders(mainPart->phdrs);
548 
549   // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
550   // 0 sized region. This has to be done late since only after assignAddresses
551   // we know the size of the sections.
552   for (Partition &part : partitions)
553     removeEmptyPTLoad(part.phdrs);
554 
555   if (!config->oFormatBinary)
556     assignFileOffsets();
557   else
558     assignFileOffsetsBinary();
559 
560   for (Partition &part : partitions)
561     setPhdrs(part);
562 
563   // Handle --print-map(-M)/--Map and --cref. Dump them before checkSections()
564   // because the files may be useful in case checkSections() or openFile()
565   // fails, for example, due to an erroneous file size.
566   writeMapAndCref();
567 
568   if (config->checkSections)
569     checkSections();
570 
571   // It does not make sense try to open the file if we have error already.
572   if (errorCount())
573     return;
574 
575   {
576     llvm::TimeTraceScope timeScope("Write output file");
577     // Write the result down to a file.
578     openFile();
579     if (errorCount())
580       return;
581 
582     if (!config->oFormatBinary) {
583       if (config->zSeparate != SeparateSegmentKind::None)
584         writeTrapInstr();
585       writeHeader();
586       writeSections();
587     } else {
588       writeSectionsBinary();
589     }
590 
591     // Backfill .note.gnu.build-id section content. This is done at last
592     // because the content is usually a hash value of the entire output file.
593     writeBuildId();
594     if (errorCount())
595       return;
596 
597     if (auto e = buffer->commit())
598       error("failed to write to the output file: " + toString(std::move(e)));
599   }
600 }
601 
602 template <class ELFT, class RelTy>
603 static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
604                                      llvm::ArrayRef<RelTy> rels) {
605   for (const RelTy &rel : rels) {
606     Symbol &sym = file->getRelocTargetSym(rel);
607     if (sym.isLocal())
608       sym.used = true;
609   }
610 }
611 
612 // The function ensures that the "used" field of local symbols reflects the fact
613 // that the symbol is used in a relocation from a live section.
614 template <class ELFT> static void markUsedLocalSymbols() {
615   // With --gc-sections, the field is already filled.
616   // See MarkLive<ELFT>::resolveReloc().
617   if (config->gcSections)
618     return;
619   for (ELFFileBase *file : objectFiles) {
620     ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
621     for (InputSectionBase *s : f->getSections()) {
622       InputSection *isec = dyn_cast_or_null<InputSection>(s);
623       if (!isec)
624         continue;
625       if (isec->type == SHT_REL)
626         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
627       else if (isec->type == SHT_RELA)
628         markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
629     }
630   }
631 }
632 
633 static bool shouldKeepInSymtab(const Defined &sym) {
634   if (sym.isSection())
635     return false;
636 
637   // If --emit-reloc or -r is given, preserve symbols referenced by relocations
638   // from live sections.
639   if (sym.used)
640     return true;
641 
642   // Exclude local symbols pointing to .ARM.exidx sections.
643   // They are probably mapping symbols "$d", which are optional for these
644   // sections. After merging the .ARM.exidx sections, some of these symbols
645   // may become dangling. The easiest way to avoid the issue is not to add
646   // them to the symbol table from the beginning.
647   if (config->emachine == EM_ARM && sym.section &&
648       sym.section->type == SHT_ARM_EXIDX)
649     return false;
650 
651   if (config->discard == DiscardPolicy::None)
652     return true;
653   if (config->discard == DiscardPolicy::All)
654     return false;
655 
656   // In ELF assembly .L symbols are normally discarded by the assembler.
657   // If the assembler fails to do so, the linker discards them if
658   // * --discard-locals is used.
659   // * The symbol is in a SHF_MERGE section, which is normally the reason for
660   //   the assembler keeping the .L symbol.
661   if (sym.getName().startswith(".L") &&
662       (config->discard == DiscardPolicy::Locals ||
663        (sym.section && (sym.section->flags & SHF_MERGE))))
664     return false;
665   return true;
666 }
667 
668 static bool includeInSymtab(const Symbol &b) {
669   if (auto *d = dyn_cast<Defined>(&b)) {
670     // Always include absolute symbols.
671     SectionBase *sec = d->section;
672     if (!sec)
673       return true;
674 
675     if (auto *s = dyn_cast<MergeInputSection>(sec))
676       return s->getSectionPiece(d->value)->live;
677     return sec->isLive();
678   }
679   return b.used || !config->gcSections;
680 }
681 
682 // Local symbols are not in the linker's symbol table. This function scans
683 // each object file's symbol table to copy local symbols to the output.
684 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
685   if (!in.symTab)
686     return;
687   llvm::TimeTraceScope timeScope("Add local symbols");
688   if (config->copyRelocs && config->discard != DiscardPolicy::None)
689     markUsedLocalSymbols<ELFT>();
690   for (ELFFileBase *file : objectFiles) {
691     for (Symbol *b : file->getLocalSymbols()) {
692       assert(b->isLocal() && "should have been caught in initializeSymbols()");
693       auto *dr = dyn_cast<Defined>(b);
694 
695       // No reason to keep local undefined symbol in symtab.
696       if (!dr)
697         continue;
698       if (includeInSymtab(*b) && shouldKeepInSymtab(*dr))
699         in.symTab->addSymbol(b);
700     }
701   }
702 }
703 
704 // Create a section symbol for each output section so that we can represent
705 // relocations that point to the section. If we know that no relocation is
706 // referring to a section (that happens if the section is a synthetic one), we
707 // don't create a section symbol for that section.
708 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
709   for (SectionCommand *cmd : script->sectionCommands) {
710     auto *osd = dyn_cast<OutputDesc>(cmd);
711     if (!osd)
712       continue;
713     OutputSection &osec = osd->osec;
714     auto i = llvm::find_if(osec.commands, [](SectionCommand *cmd) {
715       if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
716         return !isd->sections.empty();
717       return false;
718     });
719     if (i == osec.commands.end())
720       continue;
721     InputSectionBase *isec = cast<InputSectionDescription>(*i)->sections[0];
722 
723     // Relocations are not using REL[A] section symbols.
724     if (isec->type == SHT_REL || isec->type == SHT_RELA)
725       continue;
726 
727     // Unlike other synthetic sections, mergeable output sections contain data
728     // copied from input sections, and there may be a relocation pointing to its
729     // contents if -r or --emit-reloc is given.
730     if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE))
731       continue;
732 
733     // Set the symbol to be relative to the output section so that its st_value
734     // equals the output section address. Note, there may be a gap between the
735     // start of the output section and isec.
736     in.symTab->addSymbol(makeDefined(isec->file, "", STB_LOCAL, /*stOther=*/0,
737                                      STT_SECTION,
738                                      /*value=*/0, /*size=*/0, &osec));
739   }
740 }
741 
742 // Today's loaders have a feature to make segments read-only after
743 // processing dynamic relocations to enhance security. PT_GNU_RELRO
744 // is defined for that.
745 //
746 // This function returns true if a section needs to be put into a
747 // PT_GNU_RELRO segment.
748 static bool isRelroSection(const OutputSection *sec) {
749   if (!config->zRelro)
750     return false;
751 
752   uint64_t flags = sec->flags;
753 
754   // Non-allocatable or non-writable sections don't need RELRO because
755   // they are not writable or not even mapped to memory in the first place.
756   // RELRO is for sections that are essentially read-only but need to
757   // be writable only at process startup to allow dynamic linker to
758   // apply relocations.
759   if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
760     return false;
761 
762   // Once initialized, TLS data segments are used as data templates
763   // for a thread-local storage. For each new thread, runtime
764   // allocates memory for a TLS and copy templates there. No thread
765   // are supposed to use templates directly. Thus, it can be in RELRO.
766   if (flags & SHF_TLS)
767     return true;
768 
769   // .init_array, .preinit_array and .fini_array contain pointers to
770   // functions that are executed on process startup or exit. These
771   // pointers are set by the static linker, and they are not expected
772   // to change at runtime. But if you are an attacker, you could do
773   // interesting things by manipulating pointers in .fini_array, for
774   // example. So they are put into RELRO.
775   uint32_t type = sec->type;
776   if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
777       type == SHT_PREINIT_ARRAY)
778     return true;
779 
780   // .got contains pointers to external symbols. They are resolved by
781   // the dynamic linker when a module is loaded into memory, and after
782   // that they are not expected to change. So, it can be in RELRO.
783   if (in.got && sec == in.got->getParent())
784     return true;
785 
786   // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
787   // through r2 register, which is reserved for that purpose. Since r2 is used
788   // for accessing .got as well, .got and .toc need to be close enough in the
789   // virtual address space. Usually, .toc comes just after .got. Since we place
790   // .got into RELRO, .toc needs to be placed into RELRO too.
791   if (sec->name.equals(".toc"))
792     return true;
793 
794   // .got.plt contains pointers to external function symbols. They are
795   // by default resolved lazily, so we usually cannot put it into RELRO.
796   // However, if "-z now" is given, the lazy symbol resolution is
797   // disabled, which enables us to put it into RELRO.
798   if (sec == in.gotPlt->getParent())
799     return config->zNow;
800 
801   // .dynamic section contains data for the dynamic linker, and
802   // there's no need to write to it at runtime, so it's better to put
803   // it into RELRO.
804   if (sec->name == ".dynamic")
805     return true;
806 
807   // Sections with some special names are put into RELRO. This is a
808   // bit unfortunate because section names shouldn't be significant in
809   // ELF in spirit. But in reality many linker features depend on
810   // magic section names.
811   StringRef s = sec->name;
812   return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" ||
813          s == ".dtors" || s == ".jcr" || s == ".eh_frame" ||
814          s == ".fini_array" || s == ".init_array" ||
815          s == ".openbsd.randomdata" || s == ".preinit_array";
816 }
817 
818 // We compute a rank for each section. The rank indicates where the
819 // section should be placed in the file.  Instead of using simple
820 // numbers (0,1,2...), we use a series of flags. One for each decision
821 // point when placing the section.
822 // Using flags has two key properties:
823 // * It is easy to check if a give branch was taken.
824 // * It is easy two see how similar two ranks are (see getRankProximity).
825 enum RankFlags {
826   RF_NOT_ADDR_SET = 1 << 27,
827   RF_NOT_ALLOC = 1 << 26,
828   RF_PARTITION = 1 << 18, // Partition number (8 bits)
829   RF_NOT_PART_EHDR = 1 << 17,
830   RF_NOT_PART_PHDR = 1 << 16,
831   RF_NOT_INTERP = 1 << 15,
832   RF_NOT_NOTE = 1 << 14,
833   RF_WRITE = 1 << 13,
834   RF_EXEC_WRITE = 1 << 12,
835   RF_EXEC = 1 << 11,
836   RF_RODATA = 1 << 10,
837   RF_NOT_RELRO = 1 << 9,
838   RF_NOT_TLS = 1 << 8,
839   RF_BSS = 1 << 7,
840   RF_PPC_NOT_TOCBSS = 1 << 6,
841   RF_PPC_TOCL = 1 << 5,
842   RF_PPC_TOC = 1 << 4,
843   RF_PPC_GOT = 1 << 3,
844   RF_PPC_BRANCH_LT = 1 << 2,
845   RF_MIPS_GPREL = 1 << 1,
846   RF_MIPS_NOT_GOT = 1 << 0
847 };
848 
849 static unsigned getSectionRank(const OutputSection &osec) {
850   unsigned rank = osec.partition * RF_PARTITION;
851 
852   // We want to put section specified by -T option first, so we
853   // can start assigning VA starting from them later.
854   if (config->sectionStartMap.count(osec.name))
855     return rank;
856   rank |= RF_NOT_ADDR_SET;
857 
858   // Allocatable sections go first to reduce the total PT_LOAD size and
859   // so debug info doesn't change addresses in actual code.
860   if (!(osec.flags & SHF_ALLOC))
861     return rank | RF_NOT_ALLOC;
862 
863   if (osec.type == SHT_LLVM_PART_EHDR)
864     return rank;
865   rank |= RF_NOT_PART_EHDR;
866 
867   if (osec.type == SHT_LLVM_PART_PHDR)
868     return rank;
869   rank |= RF_NOT_PART_PHDR;
870 
871   // Put .interp first because some loaders want to see that section
872   // on the first page of the executable file when loaded into memory.
873   if (osec.name == ".interp")
874     return rank;
875   rank |= RF_NOT_INTERP;
876 
877   // Put .note sections (which make up one PT_NOTE) at the beginning so that
878   // they are likely to be included in a core file even if core file size is
879   // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
880   // included in a core to match core files with executables.
881   if (osec.type == SHT_NOTE)
882     return rank;
883   rank |= RF_NOT_NOTE;
884 
885   // Sort sections based on their access permission in the following
886   // order: R, RX, RWX, RW.  This order is based on the following
887   // considerations:
888   // * Read-only sections come first such that they go in the
889   //   PT_LOAD covering the program headers at the start of the file.
890   // * Read-only, executable sections come next.
891   // * Writable, executable sections follow such that .plt on
892   //   architectures where it needs to be writable will be placed
893   //   between .text and .data.
894   // * Writable sections come last, such that .bss lands at the very
895   //   end of the last PT_LOAD.
896   bool isExec = osec.flags & SHF_EXECINSTR;
897   bool isWrite = osec.flags & SHF_WRITE;
898 
899   if (isExec) {
900     if (isWrite)
901       rank |= RF_EXEC_WRITE;
902     else
903       rank |= RF_EXEC;
904   } else if (isWrite) {
905     rank |= RF_WRITE;
906   } else if (osec.type == SHT_PROGBITS) {
907     // Make non-executable and non-writable PROGBITS sections (e.g .rodata
908     // .eh_frame) closer to .text. They likely contain PC or GOT relative
909     // relocations and there could be relocation overflow if other huge sections
910     // (.dynstr .dynsym) were placed in between.
911     rank |= RF_RODATA;
912   }
913 
914   // Place RelRo sections first. After considering SHT_NOBITS below, the
915   // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss),
916   // where | marks where page alignment happens. An alternative ordering is
917   // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may
918   // waste more bytes due to 2 alignment places.
919   if (!isRelroSection(&osec))
920     rank |= RF_NOT_RELRO;
921 
922   // If we got here we know that both A and B are in the same PT_LOAD.
923 
924   // The TLS initialization block needs to be a single contiguous block in a R/W
925   // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
926   // sections. Since p_filesz can be less than p_memsz, place NOBITS sections
927   // after PROGBITS.
928   if (!(osec.flags & SHF_TLS))
929     rank |= RF_NOT_TLS;
930 
931   // Within TLS sections, or within other RelRo sections, or within non-RelRo
932   // sections, place non-NOBITS sections first.
933   if (osec.type == SHT_NOBITS)
934     rank |= RF_BSS;
935 
936   // Some architectures have additional ordering restrictions for sections
937   // within the same PT_LOAD.
938   if (config->emachine == EM_PPC64) {
939     // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
940     // that we would like to make sure appear is a specific order to maximize
941     // their coverage by a single signed 16-bit offset from the TOC base
942     // pointer. Conversely, the special .tocbss section should be first among
943     // all SHT_NOBITS sections. This will put it next to the loaded special
944     // PPC64 sections (and, thus, within reach of the TOC base pointer).
945     StringRef name = osec.name;
946     if (name != ".tocbss")
947       rank |= RF_PPC_NOT_TOCBSS;
948 
949     if (name == ".toc1")
950       rank |= RF_PPC_TOCL;
951 
952     if (name == ".toc")
953       rank |= RF_PPC_TOC;
954 
955     if (name == ".got")
956       rank |= RF_PPC_GOT;
957 
958     if (name == ".branch_lt")
959       rank |= RF_PPC_BRANCH_LT;
960   }
961 
962   if (config->emachine == EM_MIPS) {
963     // All sections with SHF_MIPS_GPREL flag should be grouped together
964     // because data in these sections is addressable with a gp relative address.
965     if (osec.flags & SHF_MIPS_GPREL)
966       rank |= RF_MIPS_GPREL;
967 
968     if (osec.name != ".got")
969       rank |= RF_MIPS_NOT_GOT;
970   }
971 
972   return rank;
973 }
974 
975 static bool compareSections(const SectionCommand *aCmd,
976                             const SectionCommand *bCmd) {
977   const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
978   const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
979 
980   if (a->sortRank != b->sortRank)
981     return a->sortRank < b->sortRank;
982 
983   if (!(a->sortRank & RF_NOT_ADDR_SET))
984     return config->sectionStartMap.lookup(a->name) <
985            config->sectionStartMap.lookup(b->name);
986   return false;
987 }
988 
989 void PhdrEntry::add(OutputSection *sec) {
990   lastSec = sec;
991   if (!firstSec)
992     firstSec = sec;
993   p_align = std::max(p_align, sec->alignment);
994   if (p_type == PT_LOAD)
995     sec->ptLoad = this;
996 }
997 
998 // The beginning and the ending of .rel[a].plt section are marked
999 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1000 // executable. The runtime needs these symbols in order to resolve
1001 // all IRELATIVE relocs on startup. For dynamic executables, we don't
1002 // need these symbols, since IRELATIVE relocs are resolved through GOT
1003 // and PLT. For details, see http://www.airs.com/blog/archives/403.
1004 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
1005   if (config->relocatable || config->isPic)
1006     return;
1007 
1008   // By default, __rela_iplt_{start,end} belong to a dummy section 0
1009   // because .rela.plt might be empty and thus removed from output.
1010   // We'll override Out::elfHeader with In.relaIplt later when we are
1011   // sure that .rela.plt exists in output.
1012   ElfSym::relaIpltStart = addOptionalRegular(
1013       config->isRela ? "__rela_iplt_start" : "__rel_iplt_start",
1014       Out::elfHeader, 0, STV_HIDDEN);
1015 
1016   ElfSym::relaIpltEnd = addOptionalRegular(
1017       config->isRela ? "__rela_iplt_end" : "__rel_iplt_end",
1018       Out::elfHeader, 0, STV_HIDDEN);
1019 }
1020 
1021 // This function generates assignments for predefined symbols (e.g. _end or
1022 // _etext) and inserts them into the commands sequence to be processed at the
1023 // appropriate time. This ensures that the value is going to be correct by the
1024 // time any references to these symbols are processed and is equivalent to
1025 // defining these symbols explicitly in the linker script.
1026 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
1027   if (ElfSym::globalOffsetTable) {
1028     // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
1029     // to the start of the .got or .got.plt section.
1030     InputSection *sec = in.gotPlt.get();
1031     if (!target->gotBaseSymInGotPlt)
1032       sec = in.mipsGot.get() ? cast<InputSection>(in.mipsGot.get())
1033                              : cast<InputSection>(in.got.get());
1034     ElfSym::globalOffsetTable->section = sec;
1035   }
1036 
1037   // .rela_iplt_{start,end} mark the start and the end of in.relaIplt.
1038   if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) {
1039     ElfSym::relaIpltStart->section = in.relaIplt.get();
1040     ElfSym::relaIpltEnd->section = in.relaIplt.get();
1041     ElfSym::relaIpltEnd->value = in.relaIplt->getSize();
1042   }
1043 
1044   PhdrEntry *last = nullptr;
1045   PhdrEntry *lastRO = nullptr;
1046 
1047   for (Partition &part : partitions) {
1048     for (PhdrEntry *p : part.phdrs) {
1049       if (p->p_type != PT_LOAD)
1050         continue;
1051       last = p;
1052       if (!(p->p_flags & PF_W))
1053         lastRO = p;
1054     }
1055   }
1056 
1057   if (lastRO) {
1058     // _etext is the first location after the last read-only loadable segment.
1059     if (ElfSym::etext1)
1060       ElfSym::etext1->section = lastRO->lastSec;
1061     if (ElfSym::etext2)
1062       ElfSym::etext2->section = lastRO->lastSec;
1063   }
1064 
1065   if (last) {
1066     // _edata points to the end of the last mapped initialized section.
1067     OutputSection *edata = nullptr;
1068     for (OutputSection *os : outputSections) {
1069       if (os->type != SHT_NOBITS)
1070         edata = os;
1071       if (os == last->lastSec)
1072         break;
1073     }
1074 
1075     if (ElfSym::edata1)
1076       ElfSym::edata1->section = edata;
1077     if (ElfSym::edata2)
1078       ElfSym::edata2->section = edata;
1079 
1080     // _end is the first location after the uninitialized data region.
1081     if (ElfSym::end1)
1082       ElfSym::end1->section = last->lastSec;
1083     if (ElfSym::end2)
1084       ElfSym::end2->section = last->lastSec;
1085   }
1086 
1087   if (ElfSym::bss)
1088     ElfSym::bss->section = findSection(".bss");
1089 
1090   // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1091   // be equal to the _gp symbol's value.
1092   if (ElfSym::mipsGp) {
1093     // Find GP-relative section with the lowest address
1094     // and use this address to calculate default _gp value.
1095     for (OutputSection *os : outputSections) {
1096       if (os->flags & SHF_MIPS_GPREL) {
1097         ElfSym::mipsGp->section = os;
1098         ElfSym::mipsGp->value = 0x7ff0;
1099         break;
1100       }
1101     }
1102   }
1103 }
1104 
1105 // We want to find how similar two ranks are.
1106 // The more branches in getSectionRank that match, the more similar they are.
1107 // Since each branch corresponds to a bit flag, we can just use
1108 // countLeadingZeros.
1109 static int getRankProximityAux(const OutputSection &a, const OutputSection &b) {
1110   return countLeadingZeros(a.sortRank ^ b.sortRank);
1111 }
1112 
1113 static int getRankProximity(OutputSection *a, SectionCommand *b) {
1114   auto *osd = dyn_cast<OutputDesc>(b);
1115   return (osd && osd->osec.hasInputSections)
1116              ? getRankProximityAux(*a, osd->osec)
1117              : -1;
1118 }
1119 
1120 // When placing orphan sections, we want to place them after symbol assignments
1121 // so that an orphan after
1122 //   begin_foo = .;
1123 //   foo : { *(foo) }
1124 //   end_foo = .;
1125 // doesn't break the intended meaning of the begin/end symbols.
1126 // We don't want to go over sections since findOrphanPos is the
1127 // one in charge of deciding the order of the sections.
1128 // We don't want to go over changes to '.', since doing so in
1129 //  rx_sec : { *(rx_sec) }
1130 //  . = ALIGN(0x1000);
1131 //  /* The RW PT_LOAD starts here*/
1132 //  rw_sec : { *(rw_sec) }
1133 // would mean that the RW PT_LOAD would become unaligned.
1134 static bool shouldSkip(SectionCommand *cmd) {
1135   if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
1136     return assign->name != ".";
1137   return false;
1138 }
1139 
1140 // We want to place orphan sections so that they share as much
1141 // characteristics with their neighbors as possible. For example, if
1142 // both are rw, or both are tls.
1143 static SmallVectorImpl<SectionCommand *>::iterator
1144 findOrphanPos(SmallVectorImpl<SectionCommand *>::iterator b,
1145               SmallVectorImpl<SectionCommand *>::iterator e) {
1146   OutputSection *sec = &cast<OutputDesc>(*e)->osec;
1147 
1148   // Find the first element that has as close a rank as possible.
1149   auto i = std::max_element(b, e, [=](SectionCommand *a, SectionCommand *b) {
1150     return getRankProximity(sec, a) < getRankProximity(sec, b);
1151   });
1152   if (i == e)
1153     return e;
1154   if (!isa<OutputDesc>(*i))
1155     return e;
1156   auto foundSec = &cast<OutputDesc>(*i)->osec;
1157 
1158   // Consider all existing sections with the same proximity.
1159   int proximity = getRankProximity(sec, *i);
1160   unsigned sortRank = sec->sortRank;
1161   if (script->hasPhdrsCommands() || !script->memoryRegions.empty())
1162     // Prevent the orphan section to be placed before the found section. If
1163     // custom program headers are defined, that helps to avoid adding it to a
1164     // previous segment and changing flags of that segment, for example, making
1165     // a read-only segment writable. If memory regions are defined, an orphan
1166     // section should continue the same region as the found section to better
1167     // resemble the behavior of GNU ld.
1168     sortRank = std::max(sortRank, foundSec->sortRank);
1169   for (; i != e; ++i) {
1170     auto *curSecDesc = dyn_cast<OutputDesc>(*i);
1171     if (!curSecDesc || !curSecDesc->osec.hasInputSections)
1172       continue;
1173     if (getRankProximity(sec, curSecDesc) != proximity ||
1174         sortRank < curSecDesc->osec.sortRank)
1175       break;
1176   }
1177 
1178   auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
1179     auto *osd = dyn_cast<OutputDesc>(cmd);
1180     return osd && osd->osec.hasInputSections;
1181   };
1182   auto j =
1183       std::find_if(std::make_reverse_iterator(i), std::make_reverse_iterator(b),
1184                    isOutputSecWithInputSections);
1185   i = j.base();
1186 
1187   // As a special case, if the orphan section is the last section, put
1188   // it at the very end, past any other commands.
1189   // This matches bfd's behavior and is convenient when the linker script fully
1190   // specifies the start of the file, but doesn't care about the end (the non
1191   // alloc sections for example).
1192   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1193   if (nextSec == e)
1194     return e;
1195 
1196   while (i != e && shouldSkip(*i))
1197     ++i;
1198   return i;
1199 }
1200 
1201 // Adds random priorities to sections not already in the map.
1202 static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
1203   if (config->shuffleSections.empty())
1204     return;
1205 
1206   SmallVector<InputSectionBase *, 0> matched, sections = inputSections;
1207   matched.reserve(sections.size());
1208   for (const auto &patAndSeed : config->shuffleSections) {
1209     matched.clear();
1210     for (InputSectionBase *sec : sections)
1211       if (patAndSeed.first.match(sec->name))
1212         matched.push_back(sec);
1213     const uint32_t seed = patAndSeed.second;
1214     if (seed == UINT32_MAX) {
1215       // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1216       // section order is stable even if the number of sections changes. This is
1217       // useful to catch issues like static initialization order fiasco
1218       // reliably.
1219       std::reverse(matched.begin(), matched.end());
1220     } else {
1221       std::mt19937 g(seed ? seed : std::random_device()());
1222       llvm::shuffle(matched.begin(), matched.end(), g);
1223     }
1224     size_t i = 0;
1225     for (InputSectionBase *&sec : sections)
1226       if (patAndSeed.first.match(sec->name))
1227         sec = matched[i++];
1228   }
1229 
1230   // Existing priorities are < 0, so use priorities >= 0 for the missing
1231   // sections.
1232   int prio = 0;
1233   for (InputSectionBase *sec : sections) {
1234     if (order.try_emplace(sec, prio).second)
1235       ++prio;
1236   }
1237 }
1238 
1239 // Builds section order for handling --symbol-ordering-file.
1240 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1241   DenseMap<const InputSectionBase *, int> sectionOrder;
1242   // Use the rarely used option --call-graph-ordering-file to sort sections.
1243   if (!config->callGraphProfile.empty())
1244     return computeCallGraphProfileOrder();
1245 
1246   if (config->symbolOrderingFile.empty())
1247     return sectionOrder;
1248 
1249   struct SymbolOrderEntry {
1250     int priority;
1251     bool present;
1252   };
1253 
1254   // Build a map from symbols to their priorities. Symbols that didn't
1255   // appear in the symbol ordering file have the lowest priority 0.
1256   // All explicitly mentioned symbols have negative (higher) priorities.
1257   DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
1258   int priority = -config->symbolOrderingFile.size();
1259   for (StringRef s : config->symbolOrderingFile)
1260     symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
1261 
1262   // Build a map from sections to their priorities.
1263   auto addSym = [&](Symbol &sym) {
1264     auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
1265     if (it == symbolOrder.end())
1266       return;
1267     SymbolOrderEntry &ent = it->second;
1268     ent.present = true;
1269 
1270     maybeWarnUnorderableSymbol(&sym);
1271 
1272     if (auto *d = dyn_cast<Defined>(&sym)) {
1273       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1274         int &priority = sectionOrder[cast<InputSectionBase>(sec)];
1275         priority = std::min(priority, ent.priority);
1276       }
1277     }
1278   };
1279 
1280   // We want both global and local symbols. We get the global ones from the
1281   // symbol table and iterate the object files for the local ones.
1282   for (Symbol *sym : symtab->symbols())
1283     addSym(*sym);
1284 
1285   for (ELFFileBase *file : objectFiles)
1286     for (Symbol *sym : file->getLocalSymbols())
1287       addSym(*sym);
1288 
1289   if (config->warnSymbolOrdering)
1290     for (auto orderEntry : symbolOrder)
1291       if (!orderEntry.second.present)
1292         warn("symbol ordering file: no such symbol: " + orderEntry.first.val());
1293 
1294   return sectionOrder;
1295 }
1296 
1297 // Sorts the sections in ISD according to the provided section order.
1298 static void
1299 sortISDBySectionOrder(InputSectionDescription *isd,
1300                       const DenseMap<const InputSectionBase *, int> &order) {
1301   SmallVector<InputSection *, 0> unorderedSections;
1302   SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
1303   uint64_t unorderedSize = 0;
1304 
1305   for (InputSection *isec : isd->sections) {
1306     auto i = order.find(isec);
1307     if (i == order.end()) {
1308       unorderedSections.push_back(isec);
1309       unorderedSize += isec->getSize();
1310       continue;
1311     }
1312     orderedSections.push_back({isec, i->second});
1313   }
1314   llvm::sort(orderedSections, llvm::less_second());
1315 
1316   // Find an insertion point for the ordered section list in the unordered
1317   // section list. On targets with limited-range branches, this is the mid-point
1318   // of the unordered section list. This decreases the likelihood that a range
1319   // extension thunk will be needed to enter or exit the ordered region. If the
1320   // ordered section list is a list of hot functions, we can generally expect
1321   // the ordered functions to be called more often than the unordered functions,
1322   // making it more likely that any particular call will be within range, and
1323   // therefore reducing the number of thunks required.
1324   //
1325   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1326   // If the layout is:
1327   //
1328   // 8MB hot
1329   // 32MB cold
1330   //
1331   // only the first 8-16MB of the cold code (depending on which hot function it
1332   // is actually calling) can call the hot code without a range extension thunk.
1333   // However, if we use this layout:
1334   //
1335   // 16MB cold
1336   // 8MB hot
1337   // 16MB cold
1338   //
1339   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1340   // of the second block of cold code can call the hot code without a thunk. So
1341   // we effectively double the amount of code that could potentially call into
1342   // the hot code without a thunk.
1343   size_t insPt = 0;
1344   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1345     uint64_t unorderedPos = 0;
1346     for (; insPt != unorderedSections.size(); ++insPt) {
1347       unorderedPos += unorderedSections[insPt]->getSize();
1348       if (unorderedPos > unorderedSize / 2)
1349         break;
1350     }
1351   }
1352 
1353   isd->sections.clear();
1354   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1355     isd->sections.push_back(isec);
1356   for (std::pair<InputSection *, int> p : orderedSections)
1357     isd->sections.push_back(p.first);
1358   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1359     isd->sections.push_back(isec);
1360 }
1361 
1362 static void sortSection(OutputSection &osec,
1363                         const DenseMap<const InputSectionBase *, int> &order) {
1364   StringRef name = osec.name;
1365 
1366   // Never sort these.
1367   if (name == ".init" || name == ".fini")
1368     return;
1369 
1370   // IRelative relocations that usually live in the .rel[a].dyn section should
1371   // be processed last by the dynamic loader. To achieve that we add synthetic
1372   // sections in the required order from the beginning so that the in.relaIplt
1373   // section is placed last in an output section. Here we just do not apply
1374   // sorting for an output section which holds the in.relaIplt section.
1375   if (in.relaIplt->getParent() == &osec)
1376     return;
1377 
1378   // Sort input sections by priority using the list provided by
1379   // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1380   // digit radix sort. The sections may be sorted stably again by a more
1381   // significant key.
1382   if (!order.empty())
1383     for (SectionCommand *b : osec.commands)
1384       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1385         sortISDBySectionOrder(isd, order);
1386 
1387   if (script->hasSectionsCommand)
1388     return;
1389 
1390   if (name == ".init_array" || name == ".fini_array") {
1391     osec.sortInitFini();
1392   } else if (name == ".ctors" || name == ".dtors") {
1393     osec.sortCtorsDtors();
1394   } else if (config->emachine == EM_PPC64 && name == ".toc") {
1395     // .toc is allocated just after .got and is accessed using GOT-relative
1396     // relocations. Object files compiled with small code model have an
1397     // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1398     // To reduce the risk of relocation overflow, .toc contents are sorted so
1399     // that sections having smaller relocation offsets are at beginning of .toc
1400     assert(osec.commands.size() == 1);
1401     auto *isd = cast<InputSectionDescription>(osec.commands[0]);
1402     llvm::stable_sort(isd->sections,
1403                       [](const InputSection *a, const InputSection *b) -> bool {
1404                         return a->file->ppc64SmallCodeModelTocRelocs &&
1405                                !b->file->ppc64SmallCodeModelTocRelocs;
1406                       });
1407   }
1408 }
1409 
1410 // If no layout was provided by linker script, we want to apply default
1411 // sorting for special input sections. This also handles --symbol-ordering-file.
1412 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1413   // Build the order once since it is expensive.
1414   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1415   maybeShuffle(order);
1416   for (SectionCommand *cmd : script->sectionCommands)
1417     if (auto *osd = dyn_cast<OutputDesc>(cmd))
1418       sortSection(osd->osec, order);
1419 }
1420 
1421 template <class ELFT> void Writer<ELFT>::sortSections() {
1422   llvm::TimeTraceScope timeScope("Sort sections");
1423 
1424   // Don't sort if using -r. It is not necessary and we want to preserve the
1425   // relative order for SHF_LINK_ORDER sections.
1426   if (config->relocatable) {
1427     script->adjustOutputSections();
1428     return;
1429   }
1430 
1431   sortInputSections();
1432 
1433   for (SectionCommand *cmd : script->sectionCommands)
1434     if (auto *osd = dyn_cast<OutputDesc>(cmd))
1435       osd->osec.sortRank = getSectionRank(osd->osec);
1436   if (!script->hasSectionsCommand) {
1437     // We know that all the OutputSections are contiguous in this case.
1438     auto isSection = [](SectionCommand *cmd) { return isa<OutputDesc>(cmd); };
1439     std::stable_sort(
1440         llvm::find_if(script->sectionCommands, isSection),
1441         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1442         compareSections);
1443   }
1444 
1445   // Process INSERT commands and update output section attributes. From this
1446   // point onwards the order of script->sectionCommands is fixed.
1447   script->processInsertCommands();
1448   script->adjustOutputSections();
1449 
1450   if (!script->hasSectionsCommand)
1451     return;
1452 
1453   // Orphan sections are sections present in the input files which are
1454   // not explicitly placed into the output file by the linker script.
1455   //
1456   // The sections in the linker script are already in the correct
1457   // order. We have to figuere out where to insert the orphan
1458   // sections.
1459   //
1460   // The order of the sections in the script is arbitrary and may not agree with
1461   // compareSections. This means that we cannot easily define a strict weak
1462   // ordering. To see why, consider a comparison of a section in the script and
1463   // one not in the script. We have a two simple options:
1464   // * Make them equivalent (a is not less than b, and b is not less than a).
1465   //   The problem is then that equivalence has to be transitive and we can
1466   //   have sections a, b and c with only b in a script and a less than c
1467   //   which breaks this property.
1468   // * Use compareSectionsNonScript. Given that the script order doesn't have
1469   //   to match, we can end up with sections a, b, c, d where b and c are in the
1470   //   script and c is compareSectionsNonScript less than b. In which case d
1471   //   can be equivalent to c, a to b and d < a. As a concrete example:
1472   //   .a (rx) # not in script
1473   //   .b (rx) # in script
1474   //   .c (ro) # in script
1475   //   .d (ro) # not in script
1476   //
1477   // The way we define an order then is:
1478   // *  Sort only the orphan sections. They are in the end right now.
1479   // *  Move each orphan section to its preferred position. We try
1480   //    to put each section in the last position where it can share
1481   //    a PT_LOAD.
1482   //
1483   // There is some ambiguity as to where exactly a new entry should be
1484   // inserted, because Commands contains not only output section
1485   // commands but also other types of commands such as symbol assignment
1486   // expressions. There's no correct answer here due to the lack of the
1487   // formal specification of the linker script. We use heuristics to
1488   // determine whether a new output command should be added before or
1489   // after another commands. For the details, look at shouldSkip
1490   // function.
1491 
1492   auto i = script->sectionCommands.begin();
1493   auto e = script->sectionCommands.end();
1494   auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
1495     if (auto *osd = dyn_cast<OutputDesc>(cmd))
1496       return osd->osec.sectionIndex == UINT32_MAX;
1497     return false;
1498   });
1499 
1500   // Sort the orphan sections.
1501   std::stable_sort(nonScriptI, e, compareSections);
1502 
1503   // As a horrible special case, skip the first . assignment if it is before any
1504   // section. We do this because it is common to set a load address by starting
1505   // the script with ". = 0xabcd" and the expectation is that every section is
1506   // after that.
1507   auto firstSectionOrDotAssignment =
1508       std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
1509   if (firstSectionOrDotAssignment != e &&
1510       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1511     ++firstSectionOrDotAssignment;
1512   i = firstSectionOrDotAssignment;
1513 
1514   while (nonScriptI != e) {
1515     auto pos = findOrphanPos(i, nonScriptI);
1516     OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
1517 
1518     // As an optimization, find all sections with the same sort rank
1519     // and insert them with one rotate.
1520     unsigned rank = orphan->sortRank;
1521     auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
1522       return cast<OutputDesc>(cmd)->osec.sortRank != rank;
1523     });
1524     std::rotate(pos, nonScriptI, end);
1525     nonScriptI = end;
1526   }
1527 
1528   script->adjustSectionsAfterSorting();
1529 }
1530 
1531 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1532   InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1533   InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1534   // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1535   // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1536   if (!la || !lb)
1537     return la && !lb;
1538   OutputSection *aOut = la->getParent();
1539   OutputSection *bOut = lb->getParent();
1540 
1541   if (aOut != bOut)
1542     return aOut->addr < bOut->addr;
1543   return la->outSecOff < lb->outSecOff;
1544 }
1545 
1546 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1547   llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1548   for (OutputSection *sec : outputSections) {
1549     if (!(sec->flags & SHF_LINK_ORDER))
1550       continue;
1551 
1552     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1553     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1554     if (!config->relocatable && config->emachine == EM_ARM &&
1555         sec->type == SHT_ARM_EXIDX)
1556       continue;
1557 
1558     // Link order may be distributed across several InputSectionDescriptions.
1559     // Sorting is performed separately.
1560     SmallVector<InputSection **, 0> scriptSections;
1561     SmallVector<InputSection *, 0> sections;
1562     for (SectionCommand *cmd : sec->commands) {
1563       auto *isd = dyn_cast<InputSectionDescription>(cmd);
1564       if (!isd)
1565         continue;
1566       bool hasLinkOrder = false;
1567       scriptSections.clear();
1568       sections.clear();
1569       for (InputSection *&isec : isd->sections) {
1570         if (isec->flags & SHF_LINK_ORDER) {
1571           InputSection *link = isec->getLinkOrderDep();
1572           if (link && !link->getParent())
1573             error(toString(isec) + ": sh_link points to discarded section " +
1574                   toString(link));
1575           hasLinkOrder = true;
1576         }
1577         scriptSections.push_back(&isec);
1578         sections.push_back(isec);
1579       }
1580       if (hasLinkOrder && errorCount() == 0) {
1581         llvm::stable_sort(sections, compareByFilePosition);
1582         for (int i = 0, n = sections.size(); i != n; ++i)
1583           *scriptSections[i] = sections[i];
1584       }
1585     }
1586   }
1587 }
1588 
1589 static void finalizeSynthetic(SyntheticSection *sec) {
1590   if (sec && sec->isNeeded() && sec->getParent()) {
1591     llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1592     sec->finalizeContents();
1593   }
1594 }
1595 
1596 // We need to generate and finalize the content that depends on the address of
1597 // InputSections. As the generation of the content may also alter InputSection
1598 // addresses we must converge to a fixed point. We do that here. See the comment
1599 // in Writer<ELFT>::finalizeSections().
1600 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1601   llvm::TimeTraceScope timeScope("Finalize address dependent content");
1602   ThunkCreator tc;
1603   AArch64Err843419Patcher a64p;
1604   ARMErr657417Patcher a32p;
1605   script->assignAddresses();
1606   // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1607   // do require the relative addresses of OutputSections because linker scripts
1608   // can assign Virtual Addresses to OutputSections that are not monotonically
1609   // increasing.
1610   for (Partition &part : partitions)
1611     finalizeSynthetic(part.armExidx.get());
1612   resolveShfLinkOrder();
1613 
1614   // Converts call x@GDPLT to call __tls_get_addr
1615   if (config->emachine == EM_HEXAGON)
1616     hexagonTLSSymbolUpdate(outputSections);
1617 
1618   int assignPasses = 0;
1619   for (;;) {
1620     bool changed = target->needsThunks && tc.createThunks(outputSections);
1621 
1622     // With Thunk Size much smaller than branch range we expect to
1623     // converge quickly; if we get to 15 something has gone wrong.
1624     if (changed && tc.pass >= 15) {
1625       error("thunk creation not converged");
1626       break;
1627     }
1628 
1629     if (config->fixCortexA53Errata843419) {
1630       if (changed)
1631         script->assignAddresses();
1632       changed |= a64p.createFixes();
1633     }
1634     if (config->fixCortexA8) {
1635       if (changed)
1636         script->assignAddresses();
1637       changed |= a32p.createFixes();
1638     }
1639 
1640     if (in.mipsGot)
1641       in.mipsGot->updateAllocSize();
1642 
1643     for (Partition &part : partitions) {
1644       changed |= part.relaDyn->updateAllocSize();
1645       if (part.relrDyn)
1646         changed |= part.relrDyn->updateAllocSize();
1647     }
1648 
1649     const Defined *changedSym = script->assignAddresses();
1650     if (!changed) {
1651       // Some symbols may be dependent on section addresses. When we break the
1652       // loop, the symbol values are finalized because a previous
1653       // assignAddresses() finalized section addresses.
1654       if (!changedSym)
1655         break;
1656       if (++assignPasses == 5) {
1657         errorOrWarn("assignment to symbol " + toString(*changedSym) +
1658                     " does not converge");
1659         break;
1660       }
1661     }
1662   }
1663 
1664   if (config->relocatable)
1665     for (OutputSection *sec : outputSections)
1666       sec->addr = 0;
1667 
1668   // If addrExpr is set, the address may not be a multiple of the alignment.
1669   // Warn because this is error-prone.
1670   for (SectionCommand *cmd : script->sectionCommands)
1671     if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1672       OutputSection *osec = &osd->osec;
1673       if (osec->addr % osec->alignment != 0)
1674         warn("address (0x" + Twine::utohexstr(osec->addr) + ") of section " +
1675              osec->name + " is not a multiple of alignment (" +
1676              Twine(osec->alignment) + ")");
1677     }
1678 }
1679 
1680 // If Input Sections have been shrunk (basic block sections) then
1681 // update symbol values and sizes associated with these sections.  With basic
1682 // block sections, input sections can shrink when the jump instructions at
1683 // the end of the section are relaxed.
1684 static void fixSymbolsAfterShrinking() {
1685   for (InputFile *File : objectFiles) {
1686     parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1687       auto *def = dyn_cast<Defined>(Sym);
1688       if (!def)
1689         return;
1690 
1691       const SectionBase *sec = def->section;
1692       if (!sec)
1693         return;
1694 
1695       const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
1696       if (!inputSec || !inputSec->bytesDropped)
1697         return;
1698 
1699       const size_t OldSize = inputSec->rawData.size();
1700       const size_t NewSize = OldSize - inputSec->bytesDropped;
1701 
1702       if (def->value > NewSize && def->value <= OldSize) {
1703         LLVM_DEBUG(llvm::dbgs()
1704                    << "Moving symbol " << Sym->getName() << " from "
1705                    << def->value << " to "
1706                    << def->value - inputSec->bytesDropped << " bytes\n");
1707         def->value -= inputSec->bytesDropped;
1708         return;
1709       }
1710 
1711       if (def->value + def->size > NewSize && def->value <= OldSize &&
1712           def->value + def->size <= OldSize) {
1713         LLVM_DEBUG(llvm::dbgs()
1714                    << "Shrinking symbol " << Sym->getName() << " from "
1715                    << def->size << " to " << def->size - inputSec->bytesDropped
1716                    << " bytes\n");
1717         def->size -= inputSec->bytesDropped;
1718       }
1719     });
1720   }
1721 }
1722 
1723 // If basic block sections exist, there are opportunities to delete fall thru
1724 // jumps and shrink jump instructions after basic block reordering.  This
1725 // relaxation pass does that.  It is only enabled when --optimize-bb-jumps
1726 // option is used.
1727 template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1728   assert(config->optimizeBBJumps);
1729 
1730   script->assignAddresses();
1731   // For every output section that has executable input sections, this
1732   // does the following:
1733   //   1. Deletes all direct jump instructions in input sections that
1734   //      jump to the following section as it is not required.
1735   //   2. If there are two consecutive jump instructions, it checks
1736   //      if they can be flipped and one can be deleted.
1737   for (OutputSection *osec : outputSections) {
1738     if (!(osec->flags & SHF_EXECINSTR))
1739       continue;
1740     SmallVector<InputSection *, 0> sections = getInputSections(*osec);
1741     size_t numDeleted = 0;
1742     // Delete all fall through jump instructions.  Also, check if two
1743     // consecutive jump instructions can be flipped so that a fall
1744     // through jmp instruction can be deleted.
1745     for (size_t i = 0, e = sections.size(); i != e; ++i) {
1746       InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1747       InputSection &sec = *sections[i];
1748       numDeleted += target->deleteFallThruJmpInsn(sec, sec.file, next);
1749     }
1750     if (numDeleted > 0) {
1751       script->assignAddresses();
1752       LLVM_DEBUG(llvm::dbgs()
1753                  << "Removing " << numDeleted << " fall through jumps\n");
1754     }
1755   }
1756 
1757   fixSymbolsAfterShrinking();
1758 
1759   for (OutputSection *osec : outputSections)
1760     for (InputSection *is : getInputSections(*osec))
1761       is->trim();
1762 }
1763 
1764 // In order to allow users to manipulate linker-synthesized sections,
1765 // we had to add synthetic sections to the input section list early,
1766 // even before we make decisions whether they are needed. This allows
1767 // users to write scripts like this: ".mygot : { .got }".
1768 //
1769 // Doing it has an unintended side effects. If it turns out that we
1770 // don't need a .got (for example) at all because there's no
1771 // relocation that needs a .got, we don't want to emit .got.
1772 //
1773 // To deal with the above problem, this function is called after
1774 // scanRelocations is called to remove synthetic sections that turn
1775 // out to be empty.
1776 static void removeUnusedSyntheticSections() {
1777   // All input synthetic sections that can be empty are placed after
1778   // all regular ones. Reverse iterate to find the first synthetic section
1779   // after a non-synthetic one which will be our starting point.
1780   auto start = std::find_if(inputSections.rbegin(), inputSections.rend(),
1781                             [](InputSectionBase *s) {
1782                               return !isa<SyntheticSection>(s);
1783                             })
1784                    .base();
1785 
1786   // Remove unused synthetic sections from inputSections;
1787   DenseSet<InputSectionBase *> unused;
1788   auto end =
1789       std::remove_if(start, inputSections.end(), [&](InputSectionBase *s) {
1790         auto *sec = cast<SyntheticSection>(s);
1791         if (sec->getParent() && sec->isNeeded())
1792           return false;
1793         unused.insert(sec);
1794         return true;
1795       });
1796   inputSections.erase(end, inputSections.end());
1797 
1798   // Remove unused synthetic sections from the corresponding input section
1799   // description and orphanSections.
1800   for (auto *sec : unused)
1801     if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
1802       for (SectionCommand *cmd : osec->commands)
1803         if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
1804           llvm::erase_if(isd->sections, [&](InputSection *isec) {
1805             return unused.count(isec);
1806           });
1807   llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {
1808     return unused.count(sec);
1809   });
1810 }
1811 
1812 // Create output section objects and add them to OutputSections.
1813 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1814   Out::preinitArray = findSection(".preinit_array");
1815   Out::initArray = findSection(".init_array");
1816   Out::finiArray = findSection(".fini_array");
1817 
1818   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1819   // symbols for sections, so that the runtime can get the start and end
1820   // addresses of each section by section name. Add such symbols.
1821   if (!config->relocatable) {
1822     addStartEndSymbols();
1823     for (SectionCommand *cmd : script->sectionCommands)
1824       if (auto *osd = dyn_cast<OutputDesc>(cmd))
1825         addStartStopSymbols(osd->osec);
1826   }
1827 
1828   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1829   // It should be okay as no one seems to care about the type.
1830   // Even the author of gold doesn't remember why gold behaves that way.
1831   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1832   if (mainPart->dynamic->parent)
1833     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
1834         /*value=*/0, /*size=*/0, mainPart->dynamic.get()})->isUsedInRegularObj = true;
1835 
1836   // Define __rel[a]_iplt_{start,end} symbols if needed.
1837   addRelIpltSymbols();
1838 
1839   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1840   // should only be defined in an executable. If .sdata does not exist, its
1841   // value/section does not matter but it has to be relative, so set its
1842   // st_shndx arbitrarily to 1 (Out::elfHeader).
1843   if (config->emachine == EM_RISCV && !config->shared) {
1844     OutputSection *sec = findSection(".sdata");
1845     ElfSym::riscvGlobalPointer =
1846         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
1847                            0x800, STV_DEFAULT);
1848   }
1849 
1850   if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
1851     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1852     // way that:
1853     //
1854     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1855     // computes 0.
1856     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1857     // the TLS block).
1858     //
1859     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1860     // an absolute symbol of zero. This is different from GNU linkers which
1861     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1862     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1863     if (s && s->isUndefined()) {
1864       s->resolve(Defined{/*file=*/nullptr, StringRef(), STB_GLOBAL, STV_HIDDEN,
1865                          STT_TLS, /*value=*/0, 0,
1866                          /*section=*/nullptr});
1867       ElfSym::tlsModuleBase = cast<Defined>(s);
1868     }
1869   }
1870 
1871   {
1872     llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1873     // This responsible for splitting up .eh_frame section into
1874     // pieces. The relocation scan uses those pieces, so this has to be
1875     // earlier.
1876     for (Partition &part : partitions)
1877       finalizeSynthetic(part.ehFrame.get());
1878   }
1879 
1880   if (config->hasDynSymTab) {
1881     parallelForEach(symtab->symbols(), [](Symbol *sym) {
1882       sym->isPreemptible = computeIsPreemptible(*sym);
1883     });
1884   }
1885 
1886   // Change values of linker-script-defined symbols from placeholders (assigned
1887   // by declareSymbols) to actual definitions.
1888   script->processSymbolAssignments();
1889 
1890   {
1891     llvm::TimeTraceScope timeScope("Scan relocations");
1892     // Scan relocations. This must be done after every symbol is declared so
1893     // that we can correctly decide if a dynamic relocation is needed. This is
1894     // called after processSymbolAssignments() because it needs to know whether
1895     // a linker-script-defined symbol is absolute.
1896     ppc64noTocRelax.clear();
1897     if (!config->relocatable) {
1898       // Scan all relocations. Each relocation goes through a series of tests to
1899       // determine if it needs special treatment, such as creating GOT, PLT,
1900       // copy relocations, etc. Note that relocations for non-alloc sections are
1901       // directly processed by InputSection::relocateNonAlloc.
1902       for (InputSectionBase *sec : inputSections)
1903         if (sec->isLive() && isa<InputSection>(sec) && (sec->flags & SHF_ALLOC))
1904           scanRelocations<ELFT>(*sec);
1905       for (Partition &part : partitions) {
1906         for (EhInputSection *sec : part.ehFrame->sections)
1907           scanRelocations<ELFT>(*sec);
1908         if (part.armExidx && part.armExidx->isLive())
1909           for (InputSection *sec : part.armExidx->exidxSections)
1910             scanRelocations<ELFT>(*sec);
1911       }
1912 
1913       reportUndefinedSymbols();
1914       postScanRelocations();
1915     }
1916   }
1917 
1918   if (in.plt && in.plt->isNeeded())
1919     in.plt->addSymbols();
1920   if (in.iplt && in.iplt->isNeeded())
1921     in.iplt->addSymbols();
1922 
1923   if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
1924     auto diagnose =
1925         config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
1926             ? errorOrWarn
1927             : warn;
1928     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
1929     // entries are seen. These cases would otherwise lead to runtime errors
1930     // reported by the dynamic linker.
1931     //
1932     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
1933     // catch more cases. That is too much for us. Our approach resembles the one
1934     // used in ld.gold, achieves a good balance to be useful but not too smart.
1935     for (SharedFile *file : sharedFiles) {
1936       bool allNeededIsKnown =
1937           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
1938             return symtab->soNames.count(CachedHashStringRef(needed));
1939           });
1940       if (!allNeededIsKnown)
1941         continue;
1942       for (Symbol *sym : file->requiredSymbols)
1943         if (sym->isUndefined() && !sym->isWeak())
1944           diagnose(toString(file) + ": undefined reference to " +
1945                    toString(*sym) + " [--no-allow-shlib-undefined]");
1946     }
1947   }
1948 
1949   {
1950     llvm::TimeTraceScope timeScope("Add symbols to symtabs");
1951     // Now that we have defined all possible global symbols including linker-
1952     // synthesized ones. Visit all symbols to give the finishing touches.
1953     for (Symbol *sym : symtab->symbols()) {
1954       if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
1955         continue;
1956       if (!config->relocatable)
1957         sym->binding = sym->computeBinding();
1958       if (in.symTab)
1959         in.symTab->addSymbol(sym);
1960 
1961       if (sym->includeInDynsym()) {
1962         partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
1963         if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
1964           if (file->isNeeded && !sym->isUndefined())
1965             addVerneed(sym);
1966       }
1967     }
1968 
1969     // We also need to scan the dynamic relocation tables of the other
1970     // partitions and add any referenced symbols to the partition's dynsym.
1971     for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
1972       DenseSet<Symbol *> syms;
1973       for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
1974         syms.insert(e.sym);
1975       for (DynamicReloc &reloc : part.relaDyn->relocs)
1976         if (reloc.sym && reloc.needsDynSymIndex() &&
1977             syms.insert(reloc.sym).second)
1978           part.dynSymTab->addSymbol(reloc.sym);
1979     }
1980   }
1981 
1982   if (in.mipsGot)
1983     in.mipsGot->build();
1984 
1985   removeUnusedSyntheticSections();
1986   script->diagnoseOrphanHandling();
1987 
1988   sortSections();
1989 
1990   // Create a list of OutputSections, assign sectionIndex, and populate
1991   // in.shStrTab.
1992   for (SectionCommand *cmd : script->sectionCommands)
1993     if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
1994       OutputSection *osec = &osd->osec;
1995       outputSections.push_back(osec);
1996       osec->sectionIndex = outputSections.size();
1997       osec->shName = in.shStrTab->addString(osec->name);
1998     }
1999 
2000   // Prefer command line supplied address over other constraints.
2001   for (OutputSection *sec : outputSections) {
2002     auto i = config->sectionStartMap.find(sec->name);
2003     if (i != config->sectionStartMap.end())
2004       sec->addrExpr = [=] { return i->second; };
2005   }
2006 
2007   // With the outputSections available check for GDPLT relocations
2008   // and add __tls_get_addr symbol if needed.
2009   if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2010     Symbol *sym = symtab->addSymbol(Undefined{
2011         nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2012     sym->isPreemptible = true;
2013     partitions[0].dynSymTab->addSymbol(sym);
2014   }
2015 
2016   // This is a bit of a hack. A value of 0 means undef, so we set it
2017   // to 1 to make __ehdr_start defined. The section number is not
2018   // particularly relevant.
2019   Out::elfHeader->sectionIndex = 1;
2020   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2021 
2022   // Binary and relocatable output does not have PHDRS.
2023   // The headers have to be created before finalize as that can influence the
2024   // image base and the dynamic section on mips includes the image base.
2025   if (!config->relocatable && !config->oFormatBinary) {
2026     for (Partition &part : partitions) {
2027       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2028                                               : createPhdrs(part);
2029       if (config->emachine == EM_ARM) {
2030         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2031         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2032       }
2033       if (config->emachine == EM_MIPS) {
2034         // Add separate segments for MIPS-specific sections.
2035         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2036         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2037         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2038       }
2039     }
2040     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2041 
2042     // Find the TLS segment. This happens before the section layout loop so that
2043     // Android relocation packing can look up TLS symbol addresses. We only need
2044     // to care about the main partition here because all TLS symbols were moved
2045     // to the main partition (see MarkLive.cpp).
2046     for (PhdrEntry *p : mainPart->phdrs)
2047       if (p->p_type == PT_TLS)
2048         Out::tlsPhdr = p;
2049   }
2050 
2051   // Some symbols are defined in term of program headers. Now that we
2052   // have the headers, we can find out which sections they point to.
2053   setReservedSymbolSections();
2054 
2055   {
2056     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2057 
2058     finalizeSynthetic(in.bss.get());
2059     finalizeSynthetic(in.bssRelRo.get());
2060     finalizeSynthetic(in.symTabShndx.get());
2061     finalizeSynthetic(in.shStrTab.get());
2062     finalizeSynthetic(in.strTab.get());
2063     finalizeSynthetic(in.got.get());
2064     finalizeSynthetic(in.mipsGot.get());
2065     finalizeSynthetic(in.igotPlt.get());
2066     finalizeSynthetic(in.gotPlt.get());
2067     finalizeSynthetic(in.relaIplt.get());
2068     finalizeSynthetic(in.relaPlt.get());
2069     finalizeSynthetic(in.plt.get());
2070     finalizeSynthetic(in.iplt.get());
2071     finalizeSynthetic(in.ppc32Got2.get());
2072     finalizeSynthetic(in.partIndex.get());
2073 
2074     // Dynamic section must be the last one in this list and dynamic
2075     // symbol table section (dynSymTab) must be the first one.
2076     for (Partition &part : partitions) {
2077       if (part.relaDyn) {
2078         // Compute DT_RELACOUNT to be used by part.dynamic.
2079         part.relaDyn->partitionRels();
2080         finalizeSynthetic(part.relaDyn.get());
2081       }
2082 
2083       finalizeSynthetic(part.dynSymTab.get());
2084       finalizeSynthetic(part.gnuHashTab.get());
2085       finalizeSynthetic(part.hashTab.get());
2086       finalizeSynthetic(part.verDef.get());
2087       finalizeSynthetic(part.relrDyn.get());
2088       finalizeSynthetic(part.ehFrameHdr.get());
2089       finalizeSynthetic(part.verSym.get());
2090       finalizeSynthetic(part.verNeed.get());
2091       finalizeSynthetic(part.dynamic.get());
2092     }
2093   }
2094 
2095   if (!script->hasSectionsCommand && !config->relocatable)
2096     fixSectionAlignments();
2097 
2098   // This is used to:
2099   // 1) Create "thunks":
2100   //    Jump instructions in many ISAs have small displacements, and therefore
2101   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
2102   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
2103   //    responsibility to create and insert small pieces of code between
2104   //    sections to extend the ranges if jump targets are out of range. Such
2105   //    code pieces are called "thunks".
2106   //
2107   //    We add thunks at this stage. We couldn't do this before this point
2108   //    because this is the earliest point where we know sizes of sections and
2109   //    their layouts (that are needed to determine if jump targets are in
2110   //    range).
2111   //
2112   // 2) Update the sections. We need to generate content that depends on the
2113   //    address of InputSections. For example, MIPS GOT section content or
2114   //    android packed relocations sections content.
2115   //
2116   // 3) Assign the final values for the linker script symbols. Linker scripts
2117   //    sometimes using forward symbol declarations. We want to set the correct
2118   //    values. They also might change after adding the thunks.
2119   finalizeAddressDependentContent();
2120 
2121   // All information needed for OutputSection part of Map file is available.
2122   if (errorCount())
2123     return;
2124 
2125   {
2126     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2127     // finalizeAddressDependentContent may have added local symbols to the
2128     // static symbol table.
2129     finalizeSynthetic(in.symTab.get());
2130     finalizeSynthetic(in.ppc64LongBranchTarget.get());
2131   }
2132 
2133   // Relaxation to delete inter-basic block jumps created by basic block
2134   // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2135   // can relax jump instructions based on symbol offset.
2136   if (config->optimizeBBJumps)
2137     optimizeBasicBlockJumps();
2138 
2139   // Fill other section headers. The dynamic table is finalized
2140   // at the end because some tags like RELSZ depend on result
2141   // of finalizing other sections.
2142   for (OutputSection *sec : outputSections)
2143     sec->finalize();
2144 }
2145 
2146 // Ensure data sections are not mixed with executable sections when
2147 // --execute-only is used. --execute-only make pages executable but not
2148 // readable.
2149 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2150   if (!config->executeOnly)
2151     return;
2152 
2153   for (OutputSection *osec : outputSections)
2154     if (osec->flags & SHF_EXECINSTR)
2155       for (InputSection *isec : getInputSections(*osec))
2156         if (!(isec->flags & SHF_EXECINSTR))
2157           error("cannot place " + toString(isec) + " into " +
2158                 toString(osec->name) +
2159                 ": --execute-only does not support intermingling data and code");
2160 }
2161 
2162 // The linker is expected to define SECNAME_start and SECNAME_end
2163 // symbols for a few sections. This function defines them.
2164 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2165   // If a section does not exist, there's ambiguity as to how we
2166   // define _start and _end symbols for an init/fini section. Since
2167   // the loader assume that the symbols are always defined, we need to
2168   // always define them. But what value? The loader iterates over all
2169   // pointers between _start and _end to run global ctors/dtors, so if
2170   // the section is empty, their symbol values don't actually matter
2171   // as long as _start and _end point to the same location.
2172   //
2173   // That said, we don't want to set the symbols to 0 (which is
2174   // probably the simplest value) because that could cause some
2175   // program to fail to link due to relocation overflow, if their
2176   // program text is above 2 GiB. We use the address of the .text
2177   // section instead to prevent that failure.
2178   //
2179   // In rare situations, the .text section may not exist. If that's the
2180   // case, use the image base address as a last resort.
2181   OutputSection *Default = findSection(".text");
2182   if (!Default)
2183     Default = Out::elfHeader;
2184 
2185   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2186     if (os && !script->isDiscarded(os)) {
2187       addOptionalRegular(start, os, 0);
2188       addOptionalRegular(end, os, -1);
2189     } else {
2190       addOptionalRegular(start, Default, 0);
2191       addOptionalRegular(end, Default, 0);
2192     }
2193   };
2194 
2195   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2196   define("__init_array_start", "__init_array_end", Out::initArray);
2197   define("__fini_array_start", "__fini_array_end", Out::finiArray);
2198 
2199   if (OutputSection *sec = findSection(".ARM.exidx"))
2200     define("__exidx_start", "__exidx_end", sec);
2201 }
2202 
2203 // If a section name is valid as a C identifier (which is rare because of
2204 // the leading '.'), linkers are expected to define __start_<secname> and
2205 // __stop_<secname> symbols. They are at beginning and end of the section,
2206 // respectively. This is not requested by the ELF standard, but GNU ld and
2207 // gold provide the feature, and used by many programs.
2208 template <class ELFT>
2209 void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
2210   StringRef s = osec.name;
2211   if (!isValidCIdentifier(s))
2212     return;
2213   addOptionalRegular(saver().save("__start_" + s), &osec, 0,
2214                      config->zStartStopVisibility);
2215   addOptionalRegular(saver().save("__stop_" + s), &osec, -1,
2216                      config->zStartStopVisibility);
2217 }
2218 
2219 static bool needsPtLoad(OutputSection *sec) {
2220   if (!(sec->flags & SHF_ALLOC))
2221     return false;
2222 
2223   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2224   // responsible for allocating space for them, not the PT_LOAD that
2225   // contains the TLS initialization image.
2226   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2227     return false;
2228   return true;
2229 }
2230 
2231 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2232 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2233 // RW. This means that there is no alignment in the RO to RX transition and we
2234 // cannot create a PT_LOAD there.
2235 static uint64_t computeFlags(uint64_t flags) {
2236   if (config->omagic)
2237     return PF_R | PF_W | PF_X;
2238   if (config->executeOnly && (flags & PF_X))
2239     return flags & ~PF_R;
2240   if (config->singleRoRx && !(flags & PF_W))
2241     return flags | PF_X;
2242   return flags;
2243 }
2244 
2245 // Decide which program headers to create and which sections to include in each
2246 // one.
2247 template <class ELFT>
2248 SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
2249   SmallVector<PhdrEntry *, 0> ret;
2250   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2251     ret.push_back(make<PhdrEntry>(type, flags));
2252     return ret.back();
2253   };
2254 
2255   unsigned partNo = part.getNumber();
2256   bool isMain = partNo == 1;
2257 
2258   // Add the first PT_LOAD segment for regular output sections.
2259   uint64_t flags = computeFlags(PF_R);
2260   PhdrEntry *load = nullptr;
2261 
2262   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2263   // PT_LOAD.
2264   if (!config->nmagic && !config->omagic) {
2265     // The first phdr entry is PT_PHDR which describes the program header
2266     // itself.
2267     if (isMain)
2268       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2269     else
2270       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2271 
2272     // PT_INTERP must be the second entry if exists.
2273     if (OutputSection *cmd = findSection(".interp", partNo))
2274       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2275 
2276     // Add the headers. We will remove them if they don't fit.
2277     // In the other partitions the headers are ordinary sections, so they don't
2278     // need to be added here.
2279     if (isMain) {
2280       load = addHdr(PT_LOAD, flags);
2281       load->add(Out::elfHeader);
2282       load->add(Out::programHeaders);
2283     }
2284   }
2285 
2286   // PT_GNU_RELRO includes all sections that should be marked as
2287   // read-only by dynamic linker after processing relocations.
2288   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2289   // an error message if more than one PT_GNU_RELRO PHDR is required.
2290   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2291   bool inRelroPhdr = false;
2292   OutputSection *relroEnd = nullptr;
2293   for (OutputSection *sec : outputSections) {
2294     if (sec->partition != partNo || !needsPtLoad(sec))
2295       continue;
2296     if (isRelroSection(sec)) {
2297       inRelroPhdr = true;
2298       if (!relroEnd)
2299         relRo->add(sec);
2300       else
2301         error("section: " + sec->name + " is not contiguous with other relro" +
2302               " sections");
2303     } else if (inRelroPhdr) {
2304       inRelroPhdr = false;
2305       relroEnd = sec;
2306     }
2307   }
2308 
2309   for (OutputSection *sec : outputSections) {
2310     if (!needsPtLoad(sec))
2311       continue;
2312 
2313     // Normally, sections in partitions other than the current partition are
2314     // ignored. But partition number 255 is a special case: it contains the
2315     // partition end marker (.part.end). It needs to be added to the main
2316     // partition so that a segment is created for it in the main partition,
2317     // which will cause the dynamic loader to reserve space for the other
2318     // partitions.
2319     if (sec->partition != partNo) {
2320       if (isMain && sec->partition == 255)
2321         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2322       continue;
2323     }
2324 
2325     // Segments are contiguous memory regions that has the same attributes
2326     // (e.g. executable or writable). There is one phdr for each segment.
2327     // Therefore, we need to create a new phdr when the next section has
2328     // different flags or is loaded at a discontiguous address or memory
2329     // region using AT or AT> linker script command, respectively. At the same
2330     // time, we don't want to create a separate load segment for the headers,
2331     // even if the first output section has an AT or AT> attribute.
2332     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2333     bool sameLMARegion =
2334         load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2335     if (!(load && newFlags == flags && sec != relroEnd &&
2336           sec->memRegion == load->firstSec->memRegion &&
2337           (sameLMARegion || load->lastSec == Out::programHeaders))) {
2338       load = addHdr(PT_LOAD, newFlags);
2339       flags = newFlags;
2340     }
2341 
2342     load->add(sec);
2343   }
2344 
2345   // Add a TLS segment if any.
2346   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2347   for (OutputSection *sec : outputSections)
2348     if (sec->partition == partNo && sec->flags & SHF_TLS)
2349       tlsHdr->add(sec);
2350   if (tlsHdr->firstSec)
2351     ret.push_back(tlsHdr);
2352 
2353   // Add an entry for .dynamic.
2354   if (OutputSection *sec = part.dynamic->getParent())
2355     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2356 
2357   if (relRo->firstSec)
2358     ret.push_back(relRo);
2359 
2360   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2361   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2362       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2363     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2364         ->add(part.ehFrameHdr->getParent());
2365 
2366   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2367   // the dynamic linker fill the segment with random data.
2368   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2369     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2370 
2371   if (config->zGnustack != GnuStackKind::None) {
2372     // PT_GNU_STACK is a special section to tell the loader to make the
2373     // pages for the stack non-executable. If you really want an executable
2374     // stack, you can pass -z execstack, but that's not recommended for
2375     // security reasons.
2376     unsigned perm = PF_R | PF_W;
2377     if (config->zGnustack == GnuStackKind::Exec)
2378       perm |= PF_X;
2379     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2380   }
2381 
2382   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2383   // is expected to perform W^X violations, such as calling mprotect(2) or
2384   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2385   // OpenBSD.
2386   if (config->zWxneeded)
2387     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2388 
2389   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2390     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2391 
2392   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2393   // same alignment.
2394   PhdrEntry *note = nullptr;
2395   for (OutputSection *sec : outputSections) {
2396     if (sec->partition != partNo)
2397       continue;
2398     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2399       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2400         note = addHdr(PT_NOTE, PF_R);
2401       note->add(sec);
2402     } else {
2403       note = nullptr;
2404     }
2405   }
2406   return ret;
2407 }
2408 
2409 template <class ELFT>
2410 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2411                                      unsigned pType, unsigned pFlags) {
2412   unsigned partNo = part.getNumber();
2413   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2414     return cmd->partition == partNo && cmd->type == shType;
2415   });
2416   if (i == outputSections.end())
2417     return;
2418 
2419   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2420   entry->add(*i);
2421   part.phdrs.push_back(entry);
2422 }
2423 
2424 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2425 // This is achieved by assigning an alignment expression to addrExpr of each
2426 // such section.
2427 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2428   const PhdrEntry *prev;
2429   auto pageAlign = [&](const PhdrEntry *p) {
2430     OutputSection *cmd = p->firstSec;
2431     if (!cmd)
2432       return;
2433     cmd->alignExpr = [align = cmd->alignment]() { return align; };
2434     if (!cmd->addrExpr) {
2435       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2436       // padding in the file contents.
2437       //
2438       // When -z separate-code is used we must not have any overlap in pages
2439       // between an executable segment and a non-executable segment. We align to
2440       // the next maximum page size boundary on transitions between executable
2441       // and non-executable segments.
2442       //
2443       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2444       // sections will be extracted to a separate file. Align to the next
2445       // maximum page size boundary so that we can find the ELF header at the
2446       // start. We cannot benefit from overlapping p_offset ranges with the
2447       // previous segment anyway.
2448       if (config->zSeparate == SeparateSegmentKind::Loadable ||
2449           (config->zSeparate == SeparateSegmentKind::Code && prev &&
2450            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2451           cmd->type == SHT_LLVM_PART_EHDR)
2452         cmd->addrExpr = [] {
2453           return alignTo(script->getDot(), config->maxPageSize);
2454         };
2455       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2456       // it must be the RW. Align to p_align(PT_TLS) to make sure
2457       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2458       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2459       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2460       // be congruent to 0 modulo p_align(PT_TLS).
2461       //
2462       // Technically this is not required, but as of 2019, some dynamic loaders
2463       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2464       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2465       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2466       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2467       // blocks correctly. We need to keep the workaround for a while.
2468       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2469         cmd->addrExpr = [] {
2470           return alignTo(script->getDot(), config->maxPageSize) +
2471                  alignTo(script->getDot() % config->maxPageSize,
2472                          Out::tlsPhdr->p_align);
2473         };
2474       else
2475         cmd->addrExpr = [] {
2476           return alignTo(script->getDot(), config->maxPageSize) +
2477                  script->getDot() % config->maxPageSize;
2478         };
2479     }
2480   };
2481 
2482   for (Partition &part : partitions) {
2483     prev = nullptr;
2484     for (const PhdrEntry *p : part.phdrs)
2485       if (p->p_type == PT_LOAD && p->firstSec) {
2486         pageAlign(p);
2487         prev = p;
2488       }
2489   }
2490 }
2491 
2492 // Compute an in-file position for a given section. The file offset must be the
2493 // same with its virtual address modulo the page size, so that the loader can
2494 // load executables without any address adjustment.
2495 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2496   // The first section in a PT_LOAD has to have congruent offset and address
2497   // modulo the maximum page size.
2498   if (os->ptLoad && os->ptLoad->firstSec == os)
2499     return alignTo(off, os->ptLoad->p_align, os->addr);
2500 
2501   // File offsets are not significant for .bss sections other than the first one
2502   // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2503   // increasing rather than setting to zero.
2504   if (os->type == SHT_NOBITS &&
2505       (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2506      return off;
2507 
2508   // If the section is not in a PT_LOAD, we just have to align it.
2509   if (!os->ptLoad)
2510     return alignTo(off, os->alignment);
2511 
2512   // If two sections share the same PT_LOAD the file offset is calculated
2513   // using this formula: Off2 = Off1 + (VA2 - VA1).
2514   OutputSection *first = os->ptLoad->firstSec;
2515   return first->offset + os->addr - first->addr;
2516 }
2517 
2518 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2519   // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2520   auto needsOffset = [](OutputSection &sec) {
2521     return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2522   };
2523   uint64_t minAddr = UINT64_MAX;
2524   for (OutputSection *sec : outputSections)
2525     if (needsOffset(*sec)) {
2526       sec->offset = sec->getLMA();
2527       minAddr = std::min(minAddr, sec->offset);
2528     }
2529 
2530   // Sections are laid out at LMA minus minAddr.
2531   fileSize = 0;
2532   for (OutputSection *sec : outputSections)
2533     if (needsOffset(*sec)) {
2534       sec->offset -= minAddr;
2535       fileSize = std::max(fileSize, sec->offset + sec->size);
2536     }
2537 }
2538 
2539 static std::string rangeToString(uint64_t addr, uint64_t len) {
2540   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2541 }
2542 
2543 // Assign file offsets to output sections.
2544 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2545   Out::programHeaders->offset = Out::elfHeader->size;
2546   uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
2547 
2548   PhdrEntry *lastRX = nullptr;
2549   for (Partition &part : partitions)
2550     for (PhdrEntry *p : part.phdrs)
2551       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2552         lastRX = p;
2553 
2554   // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2555   // will not occupy file offsets contained by a PT_LOAD.
2556   for (OutputSection *sec : outputSections) {
2557     if (!(sec->flags & SHF_ALLOC))
2558       continue;
2559     off = computeFileOffset(sec, off);
2560     sec->offset = off;
2561     if (sec->type != SHT_NOBITS)
2562       off += sec->size;
2563 
2564     // If this is a last section of the last executable segment and that
2565     // segment is the last loadable segment, align the offset of the
2566     // following section to avoid loading non-segments parts of the file.
2567     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2568         lastRX->lastSec == sec)
2569       off = alignTo(off, config->maxPageSize);
2570   }
2571   for (OutputSection *osec : outputSections)
2572     if (!(osec->flags & SHF_ALLOC)) {
2573       osec->offset = alignTo(off, osec->alignment);
2574       off = osec->offset + osec->size;
2575     }
2576 
2577   sectionHeaderOff = alignTo(off, config->wordsize);
2578   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2579 
2580   // Our logic assumes that sections have rising VA within the same segment.
2581   // With use of linker scripts it is possible to violate this rule and get file
2582   // offset overlaps or overflows. That should never happen with a valid script
2583   // which does not move the location counter backwards and usually scripts do
2584   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2585   // kernel, which control segment distribution explicitly and move the counter
2586   // backwards, so we have to allow doing that to support linking them. We
2587   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2588   // we want to prevent file size overflows because it would crash the linker.
2589   for (OutputSection *sec : outputSections) {
2590     if (sec->type == SHT_NOBITS)
2591       continue;
2592     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2593       error("unable to place section " + sec->name + " at file offset " +
2594             rangeToString(sec->offset, sec->size) +
2595             "; check your linker script for overflows");
2596   }
2597 }
2598 
2599 // Finalize the program headers. We call this function after we assign
2600 // file offsets and VAs to all sections.
2601 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2602   for (PhdrEntry *p : part.phdrs) {
2603     OutputSection *first = p->firstSec;
2604     OutputSection *last = p->lastSec;
2605 
2606     if (first) {
2607       p->p_filesz = last->offset - first->offset;
2608       if (last->type != SHT_NOBITS)
2609         p->p_filesz += last->size;
2610 
2611       p->p_memsz = last->addr + last->size - first->addr;
2612       p->p_offset = first->offset;
2613       p->p_vaddr = first->addr;
2614 
2615       // File offsets in partitions other than the main partition are relative
2616       // to the offset of the ELF headers. Perform that adjustment now.
2617       if (part.elfHeader)
2618         p->p_offset -= part.elfHeader->getParent()->offset;
2619 
2620       if (!p->hasLMA)
2621         p->p_paddr = first->getLMA();
2622     }
2623 
2624     if (p->p_type == PT_GNU_RELRO) {
2625       p->p_align = 1;
2626       // musl/glibc ld.so rounds the size down, so we need to round up
2627       // to protect the last page. This is a no-op on FreeBSD which always
2628       // rounds up.
2629       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
2630                    p->p_offset;
2631     }
2632   }
2633 }
2634 
2635 // A helper struct for checkSectionOverlap.
2636 namespace {
2637 struct SectionOffset {
2638   OutputSection *sec;
2639   uint64_t offset;
2640 };
2641 } // namespace
2642 
2643 // Check whether sections overlap for a specific address range (file offsets,
2644 // load and virtual addresses).
2645 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2646                          bool isVirtualAddr) {
2647   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2648     return a.offset < b.offset;
2649   });
2650 
2651   // Finding overlap is easy given a vector is sorted by start position.
2652   // If an element starts before the end of the previous element, they overlap.
2653   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2654     SectionOffset a = sections[i - 1];
2655     SectionOffset b = sections[i];
2656     if (b.offset >= a.offset + a.sec->size)
2657       continue;
2658 
2659     // If both sections are in OVERLAY we allow the overlapping of virtual
2660     // addresses, because it is what OVERLAY was designed for.
2661     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2662       continue;
2663 
2664     errorOrWarn("section " + a.sec->name + " " + name +
2665                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2666                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2667                 b.sec->name + " range is " +
2668                 rangeToString(b.offset, b.sec->size));
2669   }
2670 }
2671 
2672 // Check for overlapping sections and address overflows.
2673 //
2674 // In this function we check that none of the output sections have overlapping
2675 // file offsets. For SHF_ALLOC sections we also check that the load address
2676 // ranges and the virtual address ranges don't overlap
2677 template <class ELFT> void Writer<ELFT>::checkSections() {
2678   // First, check that section's VAs fit in available address space for target.
2679   for (OutputSection *os : outputSections)
2680     if ((os->addr + os->size < os->addr) ||
2681         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2682       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2683                   " of size 0x" + utohexstr(os->size) +
2684                   " exceeds available address space");
2685 
2686   // Check for overlapping file offsets. In this case we need to skip any
2687   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2688   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2689   // binary is specified only add SHF_ALLOC sections are added to the output
2690   // file so we skip any non-allocated sections in that case.
2691   std::vector<SectionOffset> fileOffs;
2692   for (OutputSection *sec : outputSections)
2693     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2694         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2695       fileOffs.push_back({sec, sec->offset});
2696   checkOverlap("file", fileOffs, false);
2697 
2698   // When linking with -r there is no need to check for overlapping virtual/load
2699   // addresses since those addresses will only be assigned when the final
2700   // executable/shared object is created.
2701   if (config->relocatable)
2702     return;
2703 
2704   // Checking for overlapping virtual and load addresses only needs to take
2705   // into account SHF_ALLOC sections since others will not be loaded.
2706   // Furthermore, we also need to skip SHF_TLS sections since these will be
2707   // mapped to other addresses at runtime and can therefore have overlapping
2708   // ranges in the file.
2709   std::vector<SectionOffset> vmas;
2710   for (OutputSection *sec : outputSections)
2711     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2712       vmas.push_back({sec, sec->addr});
2713   checkOverlap("virtual address", vmas, true);
2714 
2715   // Finally, check that the load addresses don't overlap. This will usually be
2716   // the same as the virtual addresses but can be different when using a linker
2717   // script with AT().
2718   std::vector<SectionOffset> lmas;
2719   for (OutputSection *sec : outputSections)
2720     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2721       lmas.push_back({sec, sec->getLMA()});
2722   checkOverlap("load address", lmas, false);
2723 }
2724 
2725 // The entry point address is chosen in the following ways.
2726 //
2727 // 1. the '-e' entry command-line option;
2728 // 2. the ENTRY(symbol) command in a linker control script;
2729 // 3. the value of the symbol _start, if present;
2730 // 4. the number represented by the entry symbol, if it is a number;
2731 // 5. the address 0.
2732 static uint64_t getEntryAddr() {
2733   // Case 1, 2 or 3
2734   if (Symbol *b = symtab->find(config->entry))
2735     return b->getVA();
2736 
2737   // Case 4
2738   uint64_t addr;
2739   if (to_integer(config->entry, addr))
2740     return addr;
2741 
2742   // Case 5
2743   if (config->warnMissingEntry)
2744     warn("cannot find entry symbol " + config->entry +
2745          "; not setting start address");
2746   return 0;
2747 }
2748 
2749 static uint16_t getELFType() {
2750   if (config->isPic)
2751     return ET_DYN;
2752   if (config->relocatable)
2753     return ET_REL;
2754   return ET_EXEC;
2755 }
2756 
2757 template <class ELFT> void Writer<ELFT>::writeHeader() {
2758   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2759   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2760 
2761   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2762   eHdr->e_type = getELFType();
2763   eHdr->e_entry = getEntryAddr();
2764   eHdr->e_shoff = sectionHeaderOff;
2765 
2766   // Write the section header table.
2767   //
2768   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2769   // and e_shstrndx fields. When the value of one of these fields exceeds
2770   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2771   // use fields in the section header at index 0 to store
2772   // the value. The sentinel values and fields are:
2773   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2774   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2775   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2776   size_t num = outputSections.size() + 1;
2777   if (num >= SHN_LORESERVE)
2778     sHdrs->sh_size = num;
2779   else
2780     eHdr->e_shnum = num;
2781 
2782   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2783   if (strTabIndex >= SHN_LORESERVE) {
2784     sHdrs->sh_link = strTabIndex;
2785     eHdr->e_shstrndx = SHN_XINDEX;
2786   } else {
2787     eHdr->e_shstrndx = strTabIndex;
2788   }
2789 
2790   for (OutputSection *sec : outputSections)
2791     sec->writeHeaderTo<ELFT>(++sHdrs);
2792 }
2793 
2794 // Open a result file.
2795 template <class ELFT> void Writer<ELFT>::openFile() {
2796   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2797   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2798     std::string msg;
2799     raw_string_ostream s(msg);
2800     s << "output file too large: " << Twine(fileSize) << " bytes\n"
2801       << "section sizes:\n";
2802     for (OutputSection *os : outputSections)
2803       s << os->name << ' ' << os->size << "\n";
2804     error(s.str());
2805     return;
2806   }
2807 
2808   unlinkAsync(config->outputFile);
2809   unsigned flags = 0;
2810   if (!config->relocatable)
2811     flags |= FileOutputBuffer::F_executable;
2812   if (!config->mmapOutputFile)
2813     flags |= FileOutputBuffer::F_no_mmap;
2814   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2815       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2816 
2817   if (!bufferOrErr) {
2818     error("failed to open " + config->outputFile + ": " +
2819           llvm::toString(bufferOrErr.takeError()));
2820     return;
2821   }
2822   buffer = std::move(*bufferOrErr);
2823   Out::bufferStart = buffer->getBufferStart();
2824 }
2825 
2826 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2827   for (OutputSection *sec : outputSections)
2828     if (sec->flags & SHF_ALLOC)
2829       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2830 }
2831 
2832 static void fillTrap(uint8_t *i, uint8_t *end) {
2833   for (; i + 4 <= end; i += 4)
2834     memcpy(i, &target->trapInstr, 4);
2835 }
2836 
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.
2840 //
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 : partitions) {
2845     // Fill the last page.
2846     for (PhdrEntry *p : part.phdrs)
2847       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2848         fillTrap(Out::bufferStart +
2849                      alignDown(p->firstSec->offset + p->p_filesz, 4),
2850                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2851                                             config->maxPageSize));
2852 
2853     // Round up the file size of the last segment to the page boundary iff it is
2854     // an executable segment to ensure that other tools don't accidentally
2855     // trim the instruction padding (e.g. when stripping the file).
2856     PhdrEntry *last = nullptr;
2857     for (PhdrEntry *p : part.phdrs)
2858       if (p->p_type == PT_LOAD)
2859         last = p;
2860 
2861     if (last && (last->p_flags & PF_X))
2862       last->p_memsz = last->p_filesz =
2863           alignTo(last->p_filesz, config->maxPageSize);
2864   }
2865 }
2866 
2867 // Write section contents to a mmap'ed file.
2868 template <class ELFT> void Writer<ELFT>::writeSections() {
2869   llvm::TimeTraceScope timeScope("Write sections");
2870 
2871   // In -r or --emit-relocs mode, write the relocation sections first as in
2872   // ELf_Rel targets we might find out that we need to modify the relocated
2873   // section while doing it.
2874   for (OutputSection *sec : outputSections)
2875     if (sec->type == SHT_REL || sec->type == SHT_RELA)
2876       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2877 
2878   for (OutputSection *sec : outputSections)
2879     if (sec->type != SHT_REL && sec->type != SHT_RELA)
2880       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2881 
2882   // Finally, check that all dynamic relocation addends were written correctly.
2883   if (config->checkDynamicRelocs && config->writeAddends) {
2884     for (OutputSection *sec : outputSections)
2885       if (sec->type == SHT_REL || sec->type == SHT_RELA)
2886         sec->checkDynRelAddends(Out::bufferStart);
2887   }
2888 }
2889 
2890 // Computes a hash value of Data using a given hash function.
2891 // In order to utilize multiple cores, we first split data into 1MB
2892 // chunks, compute a hash for each chunk, and then compute a hash value
2893 // of the hash values.
2894 static void
2895 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2896             llvm::ArrayRef<uint8_t> data,
2897             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2898   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2899   const size_t hashesSize = chunks.size() * hashBuf.size();
2900   std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
2901 
2902   // Compute hash values.
2903   parallelForEachN(0, chunks.size(), [&](size_t i) {
2904     hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
2905   });
2906 
2907   // Write to the final output buffer.
2908   hashFn(hashBuf.data(), makeArrayRef(hashes.get(), hashesSize));
2909 }
2910 
2911 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2912   if (!mainPart->buildId || !mainPart->buildId->getParent())
2913     return;
2914 
2915   if (config->buildId == BuildIdKind::Hexstring) {
2916     for (Partition &part : partitions)
2917       part.buildId->writeBuildId(config->buildIdVector);
2918     return;
2919   }
2920 
2921   // Compute a hash of all sections of the output file.
2922   size_t hashSize = mainPart->buildId->hashSize;
2923   std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
2924   MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
2925   llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
2926 
2927   // Fedora introduced build ID as "approximation of true uniqueness across all
2928   // binaries that might be used by overlapping sets of people". It does not
2929   // need some security goals that some hash algorithms strive to provide, e.g.
2930   // (second-)preimage and collision resistance. In practice people use 'md5'
2931   // and 'sha1' just for different lengths. Implement them with the more
2932   // efficient BLAKE3.
2933   switch (config->buildId) {
2934   case BuildIdKind::Fast:
2935     computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
2936       write64le(dest, xxHash64(arr));
2937     });
2938     break;
2939   case BuildIdKind::Md5:
2940     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2941       memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
2942     });
2943     break;
2944   case BuildIdKind::Sha1:
2945     computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
2946       memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
2947     });
2948     break;
2949   case BuildIdKind::Uuid:
2950     if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
2951       error("entropy source failure: " + ec.message());
2952     break;
2953   default:
2954     llvm_unreachable("unknown BuildIdKind");
2955   }
2956   for (Partition &part : partitions)
2957     part.buildId->writeBuildId(output);
2958 }
2959 
2960 template void elf::createSyntheticSections<ELF32LE>();
2961 template void elf::createSyntheticSections<ELF32BE>();
2962 template void elf::createSyntheticSections<ELF64LE>();
2963 template void elf::createSyntheticSections<ELF64BE>();
2964 
2965 template void elf::writeResult<ELF32LE>();
2966 template void elf::writeResult<ELF32BE>();
2967 template void elf::writeResult<ELF64LE>();
2968 template void elf::writeResult<ELF64BE>();
2969