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