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