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