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