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