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