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