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