xref: /llvm-project-15.0.7/lld/ELF/Writer.cpp (revision bbef51eb)
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())
1260     // Prevent the orphan section to be placed before the found section because
1261     // that can result in adding it to a previous segment and changing flags of
1262     // that segment, for example, making a read-only segment writable.
1263     sortRank = std::max(sortRank, foundSec->sortRank);
1264   for (; i != e; ++i) {
1265     auto *curSec = dyn_cast<OutputSection>(*i);
1266     if (!curSec || !curSec->hasInputSections)
1267       continue;
1268     if (getRankProximity(sec, curSec) != proximity ||
1269         sortRank < curSec->sortRank)
1270       break;
1271   }
1272 
1273   auto isOutputSecWithInputSections = [](BaseCommand *cmd) {
1274     auto *os = dyn_cast<OutputSection>(cmd);
1275     return os && os->hasInputSections;
1276   };
1277   auto j = std::find_if(llvm::make_reverse_iterator(i),
1278                         llvm::make_reverse_iterator(b),
1279                         isOutputSecWithInputSections);
1280   i = j.base();
1281 
1282   // As a special case, if the orphan section is the last section, put
1283   // it at the very end, past any other commands.
1284   // This matches bfd's behavior and is convenient when the linker script fully
1285   // specifies the start of the file, but doesn't care about the end (the non
1286   // alloc sections for example).
1287   auto nextSec = std::find_if(i, e, isOutputSecWithInputSections);
1288   if (nextSec == e)
1289     return e;
1290 
1291   while (i != e && shouldSkip(*i))
1292     ++i;
1293   return i;
1294 }
1295 
1296 // Adds random priorities to sections not already in the map.
1297 static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
1298   if (config->shuffleSections.empty())
1299     return;
1300 
1301   std::vector<InputSectionBase *> matched, sections = inputSections;
1302   matched.reserve(sections.size());
1303   for (const auto &patAndSeed : config->shuffleSections) {
1304     matched.clear();
1305     for (InputSectionBase *sec : sections)
1306       if (patAndSeed.first.match(sec->name))
1307         matched.push_back(sec);
1308     const uint32_t seed = patAndSeed.second;
1309     if (seed == UINT32_MAX) {
1310       // If --shuffle-sections <section-glob>=-1, reverse the section order. The
1311       // section order is stable even if the number of sections changes. This is
1312       // useful to catch issues like static initialization order fiasco
1313       // reliably.
1314       std::reverse(matched.begin(), matched.end());
1315     } else {
1316       std::mt19937 g(seed ? seed : std::random_device()());
1317       llvm::shuffle(matched.begin(), matched.end(), g);
1318     }
1319     size_t i = 0;
1320     for (InputSectionBase *&sec : sections)
1321       if (patAndSeed.first.match(sec->name))
1322         sec = matched[i++];
1323   }
1324 
1325   // Existing priorities are < 0, so use priorities >= 0 for the missing
1326   // sections.
1327   int prio = 0;
1328   for (InputSectionBase *sec : sections) {
1329     if (order.try_emplace(sec, prio).second)
1330       ++prio;
1331   }
1332 }
1333 
1334 // Builds section order for handling --symbol-ordering-file.
1335 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1336   DenseMap<const InputSectionBase *, int> sectionOrder;
1337   // Use the rarely used option --call-graph-ordering-file to sort sections.
1338   if (!config->callGraphProfile.empty())
1339     return computeCallGraphProfileOrder();
1340 
1341   if (config->symbolOrderingFile.empty())
1342     return sectionOrder;
1343 
1344   struct SymbolOrderEntry {
1345     int priority;
1346     bool present;
1347   };
1348 
1349   // Build a map from symbols to their priorities. Symbols that didn't
1350   // appear in the symbol ordering file have the lowest priority 0.
1351   // All explicitly mentioned symbols have negative (higher) priorities.
1352   DenseMap<StringRef, SymbolOrderEntry> symbolOrder;
1353   int priority = -config->symbolOrderingFile.size();
1354   for (StringRef s : config->symbolOrderingFile)
1355     symbolOrder.insert({s, {priority++, false}});
1356 
1357   // Build a map from sections to their priorities.
1358   auto addSym = [&](Symbol &sym) {
1359     auto it = symbolOrder.find(sym.getName());
1360     if (it == symbolOrder.end())
1361       return;
1362     SymbolOrderEntry &ent = it->second;
1363     ent.present = true;
1364 
1365     maybeWarnUnorderableSymbol(&sym);
1366 
1367     if (auto *d = dyn_cast<Defined>(&sym)) {
1368       if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
1369         int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)];
1370         priority = std::min(priority, ent.priority);
1371       }
1372     }
1373   };
1374 
1375   // We want both global and local symbols. We get the global ones from the
1376   // symbol table and iterate the object files for the local ones.
1377   for (Symbol *sym : symtab->symbols())
1378     if (!sym->isLazy())
1379       addSym(*sym);
1380 
1381   for (InputFile *file : objectFiles)
1382     for (Symbol *sym : file->getSymbols()) {
1383       if (!sym->isLocal())
1384         break;
1385       addSym(*sym);
1386     }
1387 
1388   if (config->warnSymbolOrdering)
1389     for (auto orderEntry : symbolOrder)
1390       if (!orderEntry.second.present)
1391         warn("symbol ordering file: no such symbol: " + orderEntry.first);
1392 
1393   return sectionOrder;
1394 }
1395 
1396 // Sorts the sections in ISD according to the provided section order.
1397 static void
1398 sortISDBySectionOrder(InputSectionDescription *isd,
1399                       const DenseMap<const InputSectionBase *, int> &order) {
1400   std::vector<InputSection *> unorderedSections;
1401   std::vector<std::pair<InputSection *, int>> orderedSections;
1402   uint64_t unorderedSize = 0;
1403 
1404   for (InputSection *isec : isd->sections) {
1405     auto i = order.find(isec);
1406     if (i == order.end()) {
1407       unorderedSections.push_back(isec);
1408       unorderedSize += isec->getSize();
1409       continue;
1410     }
1411     orderedSections.push_back({isec, i->second});
1412   }
1413   llvm::sort(orderedSections, llvm::less_second());
1414 
1415   // Find an insertion point for the ordered section list in the unordered
1416   // section list. On targets with limited-range branches, this is the mid-point
1417   // of the unordered section list. This decreases the likelihood that a range
1418   // extension thunk will be needed to enter or exit the ordered region. If the
1419   // ordered section list is a list of hot functions, we can generally expect
1420   // the ordered functions to be called more often than the unordered functions,
1421   // making it more likely that any particular call will be within range, and
1422   // therefore reducing the number of thunks required.
1423   //
1424   // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1425   // If the layout is:
1426   //
1427   // 8MB hot
1428   // 32MB cold
1429   //
1430   // only the first 8-16MB of the cold code (depending on which hot function it
1431   // is actually calling) can call the hot code without a range extension thunk.
1432   // However, if we use this layout:
1433   //
1434   // 16MB cold
1435   // 8MB hot
1436   // 16MB cold
1437   //
1438   // both the last 8-16MB of the first block of cold code and the first 8-16MB
1439   // of the second block of cold code can call the hot code without a thunk. So
1440   // we effectively double the amount of code that could potentially call into
1441   // the hot code without a thunk.
1442   size_t insPt = 0;
1443   if (target->getThunkSectionSpacing() && !orderedSections.empty()) {
1444     uint64_t unorderedPos = 0;
1445     for (; insPt != unorderedSections.size(); ++insPt) {
1446       unorderedPos += unorderedSections[insPt]->getSize();
1447       if (unorderedPos > unorderedSize / 2)
1448         break;
1449     }
1450   }
1451 
1452   isd->sections.clear();
1453   for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt))
1454     isd->sections.push_back(isec);
1455   for (std::pair<InputSection *, int> p : orderedSections)
1456     isd->sections.push_back(p.first);
1457   for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt))
1458     isd->sections.push_back(isec);
1459 }
1460 
1461 static void sortSection(OutputSection *sec,
1462                         const DenseMap<const InputSectionBase *, int> &order) {
1463   StringRef name = sec->name;
1464 
1465   // Never sort these.
1466   if (name == ".init" || name == ".fini")
1467     return;
1468 
1469   // IRelative relocations that usually live in the .rel[a].dyn section should
1470   // be processed last by the dynamic loader. To achieve that we add synthetic
1471   // sections in the required order from the beginning so that the in.relaIplt
1472   // section is placed last in an output section. Here we just do not apply
1473   // sorting for an output section which holds the in.relaIplt section.
1474   if (in.relaIplt->getParent() == sec)
1475     return;
1476 
1477   // Sort input sections by priority using the list provided by
1478   // --symbol-ordering-file or --shuffle-sections=. This is a least significant
1479   // digit radix sort. The sections may be sorted stably again by a more
1480   // significant key.
1481   if (!order.empty())
1482     for (BaseCommand *b : sec->sectionCommands)
1483       if (auto *isd = dyn_cast<InputSectionDescription>(b))
1484         sortISDBySectionOrder(isd, order);
1485 
1486   if (script->hasSectionsCommand)
1487     return;
1488 
1489   if (name == ".init_array" || name == ".fini_array") {
1490     sec->sortInitFini();
1491   } else if (name == ".ctors" || name == ".dtors") {
1492     sec->sortCtorsDtors();
1493   } else if (config->emachine == EM_PPC64 && name == ".toc") {
1494     // .toc is allocated just after .got and is accessed using GOT-relative
1495     // relocations. Object files compiled with small code model have an
1496     // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations.
1497     // To reduce the risk of relocation overflow, .toc contents are sorted so
1498     // that sections having smaller relocation offsets are at beginning of .toc
1499     assert(sec->sectionCommands.size() == 1);
1500     auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]);
1501     llvm::stable_sort(isd->sections,
1502                       [](const InputSection *a, const InputSection *b) -> bool {
1503                         return a->file->ppc64SmallCodeModelTocRelocs &&
1504                                !b->file->ppc64SmallCodeModelTocRelocs;
1505                       });
1506   }
1507 }
1508 
1509 // If no layout was provided by linker script, we want to apply default
1510 // sorting for special input sections. This also handles --symbol-ordering-file.
1511 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1512   // Build the order once since it is expensive.
1513   DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
1514   maybeShuffle(order);
1515   for (BaseCommand *base : script->sectionCommands)
1516     if (auto *sec = dyn_cast<OutputSection>(base))
1517       sortSection(sec, order);
1518 }
1519 
1520 template <class ELFT> void Writer<ELFT>::sortSections() {
1521   llvm::TimeTraceScope timeScope("Sort sections");
1522   script->adjustSectionsBeforeSorting();
1523 
1524   // Don't sort if using -r. It is not necessary and we want to preserve the
1525   // relative order for SHF_LINK_ORDER sections.
1526   if (config->relocatable)
1527     return;
1528 
1529   sortInputSections();
1530 
1531   for (BaseCommand *base : script->sectionCommands) {
1532     auto *os = dyn_cast<OutputSection>(base);
1533     if (!os)
1534       continue;
1535     os->sortRank = getSectionRank(os);
1536 
1537     // We want to assign rude approximation values to outSecOff fields
1538     // to know the relative order of the input sections. We use it for
1539     // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1540     uint64_t i = 0;
1541     for (InputSection *sec : getInputSections(os))
1542       sec->outSecOff = i++;
1543   }
1544 
1545   if (!script->hasSectionsCommand) {
1546     // We know that all the OutputSections are contiguous in this case.
1547     auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); };
1548     std::stable_sort(
1549         llvm::find_if(script->sectionCommands, isSection),
1550         llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(),
1551         compareSections);
1552 
1553     // Process INSERT commands. From this point onwards the order of
1554     // script->sectionCommands is fixed.
1555     script->processInsertCommands();
1556     return;
1557   }
1558 
1559   script->processInsertCommands();
1560 
1561   // Orphan sections are sections present in the input files which are
1562   // not explicitly placed into the output file by the linker script.
1563   //
1564   // The sections in the linker script are already in the correct
1565   // order. We have to figuere out where to insert the orphan
1566   // sections.
1567   //
1568   // The order of the sections in the script is arbitrary and may not agree with
1569   // compareSections. This means that we cannot easily define a strict weak
1570   // ordering. To see why, consider a comparison of a section in the script and
1571   // one not in the script. We have a two simple options:
1572   // * Make them equivalent (a is not less than b, and b is not less than a).
1573   //   The problem is then that equivalence has to be transitive and we can
1574   //   have sections a, b and c with only b in a script and a less than c
1575   //   which breaks this property.
1576   // * Use compareSectionsNonScript. Given that the script order doesn't have
1577   //   to match, we can end up with sections a, b, c, d where b and c are in the
1578   //   script and c is compareSectionsNonScript less than b. In which case d
1579   //   can be equivalent to c, a to b and d < a. As a concrete example:
1580   //   .a (rx) # not in script
1581   //   .b (rx) # in script
1582   //   .c (ro) # in script
1583   //   .d (ro) # not in script
1584   //
1585   // The way we define an order then is:
1586   // *  Sort only the orphan sections. They are in the end right now.
1587   // *  Move each orphan section to its preferred position. We try
1588   //    to put each section in the last position where it can share
1589   //    a PT_LOAD.
1590   //
1591   // There is some ambiguity as to where exactly a new entry should be
1592   // inserted, because Commands contains not only output section
1593   // commands but also other types of commands such as symbol assignment
1594   // expressions. There's no correct answer here due to the lack of the
1595   // formal specification of the linker script. We use heuristics to
1596   // determine whether a new output command should be added before or
1597   // after another commands. For the details, look at shouldSkip
1598   // function.
1599 
1600   auto i = script->sectionCommands.begin();
1601   auto e = script->sectionCommands.end();
1602   auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) {
1603     if (auto *sec = dyn_cast<OutputSection>(base))
1604       return sec->sectionIndex == UINT32_MAX;
1605     return false;
1606   });
1607 
1608   // Sort the orphan sections.
1609   std::stable_sort(nonScriptI, e, compareSections);
1610 
1611   // As a horrible special case, skip the first . assignment if it is before any
1612   // section. We do this because it is common to set a load address by starting
1613   // the script with ". = 0xabcd" and the expectation is that every section is
1614   // after that.
1615   auto firstSectionOrDotAssignment =
1616       std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); });
1617   if (firstSectionOrDotAssignment != e &&
1618       isa<SymbolAssignment>(**firstSectionOrDotAssignment))
1619     ++firstSectionOrDotAssignment;
1620   i = firstSectionOrDotAssignment;
1621 
1622   while (nonScriptI != e) {
1623     auto pos = findOrphanPos(i, nonScriptI);
1624     OutputSection *orphan = cast<OutputSection>(*nonScriptI);
1625 
1626     // As an optimization, find all sections with the same sort rank
1627     // and insert them with one rotate.
1628     unsigned rank = orphan->sortRank;
1629     auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) {
1630       return cast<OutputSection>(cmd)->sortRank != rank;
1631     });
1632     std::rotate(pos, nonScriptI, end);
1633     nonScriptI = end;
1634   }
1635 
1636   script->adjustSectionsAfterSorting();
1637 }
1638 
1639 static bool compareByFilePosition(InputSection *a, InputSection *b) {
1640   InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
1641   InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
1642   // SHF_LINK_ORDER sections with non-zero sh_link are ordered before
1643   // non-SHF_LINK_ORDER sections and SHF_LINK_ORDER sections with zero sh_link.
1644   if (!la || !lb)
1645     return la && !lb;
1646   OutputSection *aOut = la->getParent();
1647   OutputSection *bOut = lb->getParent();
1648 
1649   if (aOut != bOut)
1650     return aOut->addr < bOut->addr;
1651   return la->outSecOff < lb->outSecOff;
1652 }
1653 
1654 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1655   llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
1656   for (OutputSection *sec : outputSections) {
1657     if (!(sec->flags & SHF_LINK_ORDER))
1658       continue;
1659 
1660     // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated
1661     // this processing inside the ARMExidxsyntheticsection::finalizeContents().
1662     if (!config->relocatable && config->emachine == EM_ARM &&
1663         sec->type == SHT_ARM_EXIDX)
1664       continue;
1665 
1666     // Link order may be distributed across several InputSectionDescriptions.
1667     // Sorting is performed separately.
1668     std::vector<InputSection **> scriptSections;
1669     std::vector<InputSection *> sections;
1670     for (BaseCommand *base : sec->sectionCommands) {
1671       auto *isd = dyn_cast<InputSectionDescription>(base);
1672       if (!isd)
1673         continue;
1674       bool hasLinkOrder = false;
1675       scriptSections.clear();
1676       sections.clear();
1677       for (InputSection *&isec : isd->sections) {
1678         if (isec->flags & SHF_LINK_ORDER) {
1679           InputSection *link = isec->getLinkOrderDep();
1680           if (link && !link->getParent())
1681             error(toString(isec) + ": sh_link points to discarded section " +
1682                   toString(link));
1683           hasLinkOrder = true;
1684         }
1685         scriptSections.push_back(&isec);
1686         sections.push_back(isec);
1687       }
1688       if (hasLinkOrder && errorCount() == 0) {
1689         llvm::stable_sort(sections, compareByFilePosition);
1690         for (int i = 0, n = sections.size(); i != n; ++i)
1691           *scriptSections[i] = sections[i];
1692       }
1693     }
1694   }
1695 }
1696 
1697 static void finalizeSynthetic(SyntheticSection *sec) {
1698   if (sec && sec->isNeeded() && sec->getParent()) {
1699     llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
1700     sec->finalizeContents();
1701   }
1702 }
1703 
1704 // We need to generate and finalize the content that depends on the address of
1705 // InputSections. As the generation of the content may also alter InputSection
1706 // addresses we must converge to a fixed point. We do that here. See the comment
1707 // in Writer<ELFT>::finalizeSections().
1708 template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
1709   llvm::TimeTraceScope timeScope("Finalize address dependent content");
1710   ThunkCreator tc;
1711   AArch64Err843419Patcher a64p;
1712   ARMErr657417Patcher a32p;
1713   script->assignAddresses();
1714   // .ARM.exidx and SHF_LINK_ORDER do not require precise addresses, but they
1715   // do require the relative addresses of OutputSections because linker scripts
1716   // can assign Virtual Addresses to OutputSections that are not monotonically
1717   // increasing.
1718   for (Partition &part : partitions)
1719     finalizeSynthetic(part.armExidx);
1720   resolveShfLinkOrder();
1721 
1722   // Converts call x@GDPLT to call __tls_get_addr
1723   if (config->emachine == EM_HEXAGON)
1724     hexagonTLSSymbolUpdate(outputSections);
1725 
1726   int assignPasses = 0;
1727   for (;;) {
1728     bool changed = target->needsThunks && tc.createThunks(outputSections);
1729 
1730     // With Thunk Size much smaller than branch range we expect to
1731     // converge quickly; if we get to 15 something has gone wrong.
1732     if (changed && tc.pass >= 15) {
1733       error("thunk creation not converged");
1734       break;
1735     }
1736 
1737     if (config->fixCortexA53Errata843419) {
1738       if (changed)
1739         script->assignAddresses();
1740       changed |= a64p.createFixes();
1741     }
1742     if (config->fixCortexA8) {
1743       if (changed)
1744         script->assignAddresses();
1745       changed |= a32p.createFixes();
1746     }
1747 
1748     if (in.mipsGot)
1749       in.mipsGot->updateAllocSize();
1750 
1751     for (Partition &part : partitions) {
1752       changed |= part.relaDyn->updateAllocSize();
1753       if (part.relrDyn)
1754         changed |= part.relrDyn->updateAllocSize();
1755     }
1756 
1757     const Defined *changedSym = script->assignAddresses();
1758     if (!changed) {
1759       // Some symbols may be dependent on section addresses. When we break the
1760       // loop, the symbol values are finalized because a previous
1761       // assignAddresses() finalized section addresses.
1762       if (!changedSym)
1763         break;
1764       if (++assignPasses == 5) {
1765         errorOrWarn("assignment to symbol " + toString(*changedSym) +
1766                     " does not converge");
1767         break;
1768       }
1769     }
1770   }
1771 
1772   // If addrExpr is set, the address may not be a multiple of the alignment.
1773   // Warn because this is error-prone.
1774   for (BaseCommand *cmd : script->sectionCommands)
1775     if (auto *os = dyn_cast<OutputSection>(cmd))
1776       if (os->addr % os->alignment != 0)
1777         warn("address (0x" + Twine::utohexstr(os->addr) + ") of section " +
1778              os->name + " is not a multiple of alignment (" +
1779              Twine(os->alignment) + ")");
1780 }
1781 
1782 // If Input Sections have been shrunk (basic block sections) then
1783 // update symbol values and sizes associated with these sections.  With basic
1784 // block sections, input sections can shrink when the jump instructions at
1785 // the end of the section are relaxed.
1786 static void fixSymbolsAfterShrinking() {
1787   for (InputFile *File : objectFiles) {
1788     parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
1789       auto *def = dyn_cast<Defined>(Sym);
1790       if (!def)
1791         return;
1792 
1793       const SectionBase *sec = def->section;
1794       if (!sec)
1795         return;
1796 
1797       const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec->repl);
1798       if (!inputSec || !inputSec->bytesDropped)
1799         return;
1800 
1801       const size_t OldSize = inputSec->data().size();
1802       const size_t NewSize = OldSize - inputSec->bytesDropped;
1803 
1804       if (def->value > NewSize && def->value <= OldSize) {
1805         LLVM_DEBUG(llvm::dbgs()
1806                    << "Moving symbol " << Sym->getName() << " from "
1807                    << def->value << " to "
1808                    << def->value - inputSec->bytesDropped << " bytes\n");
1809         def->value -= inputSec->bytesDropped;
1810         return;
1811       }
1812 
1813       if (def->value + def->size > NewSize && def->value <= OldSize &&
1814           def->value + def->size <= OldSize) {
1815         LLVM_DEBUG(llvm::dbgs()
1816                    << "Shrinking symbol " << Sym->getName() << " from "
1817                    << def->size << " to " << def->size - inputSec->bytesDropped
1818                    << " bytes\n");
1819         def->size -= inputSec->bytesDropped;
1820       }
1821     });
1822   }
1823 }
1824 
1825 // If basic block sections exist, there are opportunities to delete fall thru
1826 // jumps and shrink jump instructions after basic block reordering.  This
1827 // relaxation pass does that.  It is only enabled when --optimize-bb-jumps
1828 // option is used.
1829 template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
1830   assert(config->optimizeBBJumps);
1831 
1832   script->assignAddresses();
1833   // For every output section that has executable input sections, this
1834   // does the following:
1835   //   1. Deletes all direct jump instructions in input sections that
1836   //      jump to the following section as it is not required.
1837   //   2. If there are two consecutive jump instructions, it checks
1838   //      if they can be flipped and one can be deleted.
1839   for (OutputSection *os : outputSections) {
1840     if (!(os->flags & SHF_EXECINSTR))
1841       continue;
1842     std::vector<InputSection *> sections = getInputSections(os);
1843     std::vector<unsigned> result(sections.size());
1844     // Delete all fall through jump instructions.  Also, check if two
1845     // consecutive jump instructions can be flipped so that a fall
1846     // through jmp instruction can be deleted.
1847     parallelForEachN(0, sections.size(), [&](size_t i) {
1848       InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
1849       InputSection &is = *sections[i];
1850       result[i] =
1851           target->deleteFallThruJmpInsn(is, is.getFile<ELFT>(), next) ? 1 : 0;
1852     });
1853     size_t numDeleted = std::count(result.begin(), result.end(), 1);
1854     if (numDeleted > 0) {
1855       script->assignAddresses();
1856       LLVM_DEBUG(llvm::dbgs()
1857                  << "Removing " << numDeleted << " fall through jumps\n");
1858     }
1859   }
1860 
1861   fixSymbolsAfterShrinking();
1862 
1863   for (OutputSection *os : outputSections) {
1864     std::vector<InputSection *> sections = getInputSections(os);
1865     for (InputSection *is : sections)
1866       is->trim();
1867   }
1868 }
1869 
1870 // In order to allow users to manipulate linker-synthesized sections,
1871 // we had to add synthetic sections to the input section list early,
1872 // even before we make decisions whether they are needed. This allows
1873 // users to write scripts like this: ".mygot : { .got }".
1874 //
1875 // Doing it has an unintended side effects. If it turns out that we
1876 // don't need a .got (for example) at all because there's no
1877 // relocation that needs a .got, we don't want to emit .got.
1878 //
1879 // To deal with the above problem, this function is called after
1880 // scanRelocations is called to remove synthetic sections that turn
1881 // out to be empty.
1882 static void removeUnusedSyntheticSections() {
1883   // All input synthetic sections that can be empty are placed after
1884   // all regular ones. Reverse iterate to find the first synthetic section
1885   // after a non-synthetic one which will be our starting point.
1886   auto start = std::find_if(inputSections.rbegin(), inputSections.rend(),
1887                             [](InputSectionBase *s) {
1888                               return !isa<SyntheticSection>(s);
1889                             })
1890                    .base();
1891 
1892   DenseSet<InputSectionDescription *> isdSet;
1893   // Mark unused synthetic sections for deletion
1894   auto end = std::stable_partition(
1895       start, inputSections.end(), [&](InputSectionBase *s) {
1896         SyntheticSection *ss = dyn_cast<SyntheticSection>(s);
1897         OutputSection *os = ss->getParent();
1898         if (!os || ss->isNeeded())
1899           return true;
1900 
1901         // If we reach here, then ss is an unused synthetic section and we want
1902         // to remove it from the corresponding input section description, and
1903         // orphanSections.
1904         for (BaseCommand *b : os->sectionCommands)
1905           if (auto *isd = dyn_cast<InputSectionDescription>(b))
1906             isdSet.insert(isd);
1907 
1908         llvm::erase_if(
1909             script->orphanSections,
1910             [=](const InputSectionBase *isec) { return isec == ss; });
1911 
1912         return false;
1913       });
1914 
1915   DenseSet<InputSectionBase *> unused(end, inputSections.end());
1916   for (auto *isd : isdSet)
1917     llvm::erase_if(isd->sections,
1918                    [=](InputSection *isec) { return unused.count(isec); });
1919 
1920   // Erase unused synthetic sections.
1921   inputSections.erase(end, inputSections.end());
1922 }
1923 
1924 // Create output section objects and add them to OutputSections.
1925 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1926   Out::preinitArray = findSection(".preinit_array");
1927   Out::initArray = findSection(".init_array");
1928   Out::finiArray = findSection(".fini_array");
1929 
1930   // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1931   // symbols for sections, so that the runtime can get the start and end
1932   // addresses of each section by section name. Add such symbols.
1933   if (!config->relocatable) {
1934     addStartEndSymbols();
1935     for (BaseCommand *base : script->sectionCommands)
1936       if (auto *sec = dyn_cast<OutputSection>(base))
1937         addStartStopSymbols(sec);
1938   }
1939 
1940   // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1941   // It should be okay as no one seems to care about the type.
1942   // Even the author of gold doesn't remember why gold behaves that way.
1943   // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1944   if (mainPart->dynamic->parent)
1945     symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK,
1946                               STV_HIDDEN, STT_NOTYPE,
1947                               /*value=*/0, /*size=*/0, mainPart->dynamic});
1948 
1949   // Define __rel[a]_iplt_{start,end} symbols if needed.
1950   addRelIpltSymbols();
1951 
1952   // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol
1953   // should only be defined in an executable. If .sdata does not exist, its
1954   // value/section does not matter but it has to be relative, so set its
1955   // st_shndx arbitrarily to 1 (Out::elfHeader).
1956   if (config->emachine == EM_RISCV && !config->shared) {
1957     OutputSection *sec = findSection(".sdata");
1958     ElfSym::riscvGlobalPointer =
1959         addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader,
1960                            0x800, STV_DEFAULT);
1961   }
1962 
1963   if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
1964     // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a
1965     // way that:
1966     //
1967     // 1) Without relaxation: it produces a dynamic TLSDESC relocation that
1968     // computes 0.
1969     // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
1970     // the TLS block).
1971     //
1972     // 2) is special cased in @tpoff computation. To satisfy 1), we define it as
1973     // an absolute symbol of zero. This is different from GNU linkers which
1974     // define _TLS_MODULE_BASE_ relative to the first TLS section.
1975     Symbol *s = symtab->find("_TLS_MODULE_BASE_");
1976     if (s && s->isUndefined()) {
1977       s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN,
1978                          STT_TLS, /*value=*/0, 0,
1979                          /*section=*/nullptr});
1980       ElfSym::tlsModuleBase = cast<Defined>(s);
1981     }
1982   }
1983 
1984   {
1985     llvm::TimeTraceScope timeScope("Finalize .eh_frame");
1986     // This responsible for splitting up .eh_frame section into
1987     // pieces. The relocation scan uses those pieces, so this has to be
1988     // earlier.
1989     for (Partition &part : partitions)
1990       finalizeSynthetic(part.ehFrame);
1991   }
1992 
1993   for (Symbol *sym : symtab->symbols())
1994     sym->isPreemptible = computeIsPreemptible(*sym);
1995 
1996   // Change values of linker-script-defined symbols from placeholders (assigned
1997   // by declareSymbols) to actual definitions.
1998   script->processSymbolAssignments();
1999 
2000   {
2001     llvm::TimeTraceScope timeScope("Scan relocations");
2002     // Scan relocations. This must be done after every symbol is declared so
2003     // that we can correctly decide if a dynamic relocation is needed. This is
2004     // called after processSymbolAssignments() because it needs to know whether
2005     // a linker-script-defined symbol is absolute.
2006     ppc64noTocRelax.clear();
2007     if (!config->relocatable) {
2008       forEachRelSec(scanRelocations<ELFT>);
2009       reportUndefinedSymbols<ELFT>();
2010     }
2011   }
2012 
2013   if (in.plt && in.plt->isNeeded())
2014     in.plt->addSymbols();
2015   if (in.iplt && in.iplt->isNeeded())
2016     in.iplt->addSymbols();
2017 
2018   if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
2019     auto diagnose =
2020         config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
2021             ? errorOrWarn
2022             : warn;
2023     // Error on undefined symbols in a shared object, if all of its DT_NEEDED
2024     // entries are seen. These cases would otherwise lead to runtime errors
2025     // reported by the dynamic linker.
2026     //
2027     // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to
2028     // catch more cases. That is too much for us. Our approach resembles the one
2029     // used in ld.gold, achieves a good balance to be useful but not too smart.
2030     for (SharedFile *file : sharedFiles) {
2031       bool allNeededIsKnown =
2032           llvm::all_of(file->dtNeeded, [&](StringRef needed) {
2033             return symtab->soNames.count(needed);
2034           });
2035       if (!allNeededIsKnown)
2036         continue;
2037       for (Symbol *sym : file->requiredSymbols)
2038         if (sym->isUndefined() && !sym->isWeak())
2039           diagnose(toString(file) + ": undefined reference to " +
2040                    toString(*sym) + " [--no-allow-shlib-undefined]");
2041     }
2042   }
2043 
2044   {
2045     llvm::TimeTraceScope timeScope("Add symbols to symtabs");
2046     // Now that we have defined all possible global symbols including linker-
2047     // synthesized ones. Visit all symbols to give the finishing touches.
2048     for (Symbol *sym : symtab->symbols()) {
2049       if (!includeInSymtab(*sym))
2050         continue;
2051       if (in.symTab)
2052         in.symTab->addSymbol(sym);
2053 
2054       if (sym->includeInDynsym()) {
2055         partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
2056         if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
2057           if (file->isNeeded && !sym->isUndefined())
2058             addVerneed(sym);
2059       }
2060     }
2061 
2062     // We also need to scan the dynamic relocation tables of the other
2063     // partitions and add any referenced symbols to the partition's dynsym.
2064     for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
2065       DenseSet<Symbol *> syms;
2066       for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
2067         syms.insert(e.sym);
2068       for (DynamicReloc &reloc : part.relaDyn->relocs)
2069         if (reloc.sym && reloc.needsDynSymIndex() &&
2070             syms.insert(reloc.sym).second)
2071           part.dynSymTab->addSymbol(reloc.sym);
2072     }
2073   }
2074 
2075   // Do not proceed if there was an undefined symbol.
2076   if (errorCount())
2077     return;
2078 
2079   if (in.mipsGot)
2080     in.mipsGot->build();
2081 
2082   removeUnusedSyntheticSections();
2083   script->diagnoseOrphanHandling();
2084 
2085   sortSections();
2086 
2087   // Now that we have the final list, create a list of all the
2088   // OutputSections for convenience.
2089   for (BaseCommand *base : script->sectionCommands)
2090     if (auto *sec = dyn_cast<OutputSection>(base))
2091       outputSections.push_back(sec);
2092 
2093   // Prefer command line supplied address over other constraints.
2094   for (OutputSection *sec : outputSections) {
2095     auto i = config->sectionStartMap.find(sec->name);
2096     if (i != config->sectionStartMap.end())
2097       sec->addrExpr = [=] { return i->second; };
2098   }
2099 
2100   // With the outputSections available check for GDPLT relocations
2101   // and add __tls_get_addr symbol if needed.
2102   if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
2103     Symbol *sym = symtab->addSymbol(Undefined{
2104         nullptr, "__tls_get_addr", STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
2105     sym->isPreemptible = true;
2106     partitions[0].dynSymTab->addSymbol(sym);
2107   }
2108 
2109   // This is a bit of a hack. A value of 0 means undef, so we set it
2110   // to 1 to make __ehdr_start defined. The section number is not
2111   // particularly relevant.
2112   Out::elfHeader->sectionIndex = 1;
2113 
2114   for (size_t i = 0, e = outputSections.size(); i != e; ++i) {
2115     OutputSection *sec = outputSections[i];
2116     sec->sectionIndex = i + 1;
2117     sec->shName = in.shStrTab->addString(sec->name);
2118   }
2119 
2120   // Binary and relocatable output does not have PHDRS.
2121   // The headers have to be created before finalize as that can influence the
2122   // image base and the dynamic section on mips includes the image base.
2123   if (!config->relocatable && !config->oFormatBinary) {
2124     for (Partition &part : partitions) {
2125       part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
2126                                               : createPhdrs(part);
2127       if (config->emachine == EM_ARM) {
2128         // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2129         addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
2130       }
2131       if (config->emachine == EM_MIPS) {
2132         // Add separate segments for MIPS-specific sections.
2133         addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
2134         addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
2135         addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
2136       }
2137     }
2138     Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
2139 
2140     // Find the TLS segment. This happens before the section layout loop so that
2141     // Android relocation packing can look up TLS symbol addresses. We only need
2142     // to care about the main partition here because all TLS symbols were moved
2143     // to the main partition (see MarkLive.cpp).
2144     for (PhdrEntry *p : mainPart->phdrs)
2145       if (p->p_type == PT_TLS)
2146         Out::tlsPhdr = p;
2147   }
2148 
2149   // Some symbols are defined in term of program headers. Now that we
2150   // have the headers, we can find out which sections they point to.
2151   setReservedSymbolSections();
2152 
2153   {
2154     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2155 
2156     finalizeSynthetic(in.bss);
2157     finalizeSynthetic(in.bssRelRo);
2158     finalizeSynthetic(in.symTabShndx);
2159     finalizeSynthetic(in.shStrTab);
2160     finalizeSynthetic(in.strTab);
2161     finalizeSynthetic(in.got);
2162     finalizeSynthetic(in.mipsGot);
2163     finalizeSynthetic(in.igotPlt);
2164     finalizeSynthetic(in.gotPlt);
2165     finalizeSynthetic(in.relaIplt);
2166     finalizeSynthetic(in.relaPlt);
2167     finalizeSynthetic(in.plt);
2168     finalizeSynthetic(in.iplt);
2169     finalizeSynthetic(in.ppc32Got2);
2170     finalizeSynthetic(in.partIndex);
2171 
2172     // Dynamic section must be the last one in this list and dynamic
2173     // symbol table section (dynSymTab) must be the first one.
2174     for (Partition &part : partitions) {
2175       finalizeSynthetic(part.dynSymTab);
2176       finalizeSynthetic(part.gnuHashTab);
2177       finalizeSynthetic(part.hashTab);
2178       finalizeSynthetic(part.verDef);
2179       finalizeSynthetic(part.relaDyn);
2180       finalizeSynthetic(part.relrDyn);
2181       finalizeSynthetic(part.ehFrameHdr);
2182       finalizeSynthetic(part.verSym);
2183       finalizeSynthetic(part.verNeed);
2184       finalizeSynthetic(part.dynamic);
2185     }
2186   }
2187 
2188   if (!script->hasSectionsCommand && !config->relocatable)
2189     fixSectionAlignments();
2190 
2191   // This is used to:
2192   // 1) Create "thunks":
2193   //    Jump instructions in many ISAs have small displacements, and therefore
2194   //    they cannot jump to arbitrary addresses in memory. For example, RISC-V
2195   //    JAL instruction can target only +-1 MiB from PC. It is a linker's
2196   //    responsibility to create and insert small pieces of code between
2197   //    sections to extend the ranges if jump targets are out of range. Such
2198   //    code pieces are called "thunks".
2199   //
2200   //    We add thunks at this stage. We couldn't do this before this point
2201   //    because this is the earliest point where we know sizes of sections and
2202   //    their layouts (that are needed to determine if jump targets are in
2203   //    range).
2204   //
2205   // 2) Update the sections. We need to generate content that depends on the
2206   //    address of InputSections. For example, MIPS GOT section content or
2207   //    android packed relocations sections content.
2208   //
2209   // 3) Assign the final values for the linker script symbols. Linker scripts
2210   //    sometimes using forward symbol declarations. We want to set the correct
2211   //    values. They also might change after adding the thunks.
2212   finalizeAddressDependentContent();
2213   if (errorCount())
2214     return;
2215 
2216   {
2217     llvm::TimeTraceScope timeScope("Finalize synthetic sections");
2218     // finalizeAddressDependentContent may have added local symbols to the
2219     // static symbol table.
2220     finalizeSynthetic(in.symTab);
2221     finalizeSynthetic(in.ppc64LongBranchTarget);
2222   }
2223 
2224   // Relaxation to delete inter-basic block jumps created by basic block
2225   // sections. Run after in.symTab is finalized as optimizeBasicBlockJumps
2226   // can relax jump instructions based on symbol offset.
2227   if (config->optimizeBBJumps)
2228     optimizeBasicBlockJumps();
2229 
2230   // Fill other section headers. The dynamic table is finalized
2231   // at the end because some tags like RELSZ depend on result
2232   // of finalizing other sections.
2233   for (OutputSection *sec : outputSections)
2234     sec->finalize();
2235 }
2236 
2237 // Ensure data sections are not mixed with executable sections when
2238 // --execute-only is used. --execute-only make pages executable but not
2239 // readable.
2240 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
2241   if (!config->executeOnly)
2242     return;
2243 
2244   for (OutputSection *os : outputSections)
2245     if (os->flags & SHF_EXECINSTR)
2246       for (InputSection *isec : getInputSections(os))
2247         if (!(isec->flags & SHF_EXECINSTR))
2248           error("cannot place " + toString(isec) + " into " + toString(os->name) +
2249                 ": -execute-only does not support intermingling data and code");
2250 }
2251 
2252 // The linker is expected to define SECNAME_start and SECNAME_end
2253 // symbols for a few sections. This function defines them.
2254 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
2255   // If a section does not exist, there's ambiguity as to how we
2256   // define _start and _end symbols for an init/fini section. Since
2257   // the loader assume that the symbols are always defined, we need to
2258   // always define them. But what value? The loader iterates over all
2259   // pointers between _start and _end to run global ctors/dtors, so if
2260   // the section is empty, their symbol values don't actually matter
2261   // as long as _start and _end point to the same location.
2262   //
2263   // That said, we don't want to set the symbols to 0 (which is
2264   // probably the simplest value) because that could cause some
2265   // program to fail to link due to relocation overflow, if their
2266   // program text is above 2 GiB. We use the address of the .text
2267   // section instead to prevent that failure.
2268   //
2269   // In rare situations, the .text section may not exist. If that's the
2270   // case, use the image base address as a last resort.
2271   OutputSection *Default = findSection(".text");
2272   if (!Default)
2273     Default = Out::elfHeader;
2274 
2275   auto define = [=](StringRef start, StringRef end, OutputSection *os) {
2276     if (os) {
2277       addOptionalRegular(start, os, 0);
2278       addOptionalRegular(end, os, -1);
2279     } else {
2280       addOptionalRegular(start, Default, 0);
2281       addOptionalRegular(end, Default, 0);
2282     }
2283   };
2284 
2285   define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
2286   define("__init_array_start", "__init_array_end", Out::initArray);
2287   define("__fini_array_start", "__fini_array_end", Out::finiArray);
2288 
2289   if (OutputSection *sec = findSection(".ARM.exidx"))
2290     define("__exidx_start", "__exidx_end", sec);
2291 }
2292 
2293 // If a section name is valid as a C identifier (which is rare because of
2294 // the leading '.'), linkers are expected to define __start_<secname> and
2295 // __stop_<secname> symbols. They are at beginning and end of the section,
2296 // respectively. This is not requested by the ELF standard, but GNU ld and
2297 // gold provide the feature, and used by many programs.
2298 template <class ELFT>
2299 void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) {
2300   StringRef s = sec->name;
2301   if (!isValidCIdentifier(s))
2302     return;
2303   addOptionalRegular(saver.save("__start_" + s), sec, 0,
2304                      config->zStartStopVisibility);
2305   addOptionalRegular(saver.save("__stop_" + s), sec, -1,
2306                      config->zStartStopVisibility);
2307 }
2308 
2309 static bool needsPtLoad(OutputSection *sec) {
2310   if (!(sec->flags & SHF_ALLOC))
2311     return false;
2312 
2313   // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
2314   // responsible for allocating space for them, not the PT_LOAD that
2315   // contains the TLS initialization image.
2316   if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
2317     return false;
2318   return true;
2319 }
2320 
2321 // Linker scripts are responsible for aligning addresses. Unfortunately, most
2322 // linker scripts are designed for creating two PT_LOADs only, one RX and one
2323 // RW. This means that there is no alignment in the RO to RX transition and we
2324 // cannot create a PT_LOAD there.
2325 static uint64_t computeFlags(uint64_t flags) {
2326   if (config->omagic)
2327     return PF_R | PF_W | PF_X;
2328   if (config->executeOnly && (flags & PF_X))
2329     return flags & ~PF_R;
2330   if (config->singleRoRx && !(flags & PF_W))
2331     return flags | PF_X;
2332   return flags;
2333 }
2334 
2335 // Decide which program headers to create and which sections to include in each
2336 // one.
2337 template <class ELFT>
2338 std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) {
2339   std::vector<PhdrEntry *> ret;
2340   auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
2341     ret.push_back(make<PhdrEntry>(type, flags));
2342     return ret.back();
2343   };
2344 
2345   unsigned partNo = part.getNumber();
2346   bool isMain = partNo == 1;
2347 
2348   // Add the first PT_LOAD segment for regular output sections.
2349   uint64_t flags = computeFlags(PF_R);
2350   PhdrEntry *load = nullptr;
2351 
2352   // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly
2353   // PT_LOAD.
2354   if (!config->nmagic && !config->omagic) {
2355     // The first phdr entry is PT_PHDR which describes the program header
2356     // itself.
2357     if (isMain)
2358       addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
2359     else
2360       addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
2361 
2362     // PT_INTERP must be the second entry if exists.
2363     if (OutputSection *cmd = findSection(".interp", partNo))
2364       addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
2365 
2366     // Add the headers. We will remove them if they don't fit.
2367     // In the other partitions the headers are ordinary sections, so they don't
2368     // need to be added here.
2369     if (isMain) {
2370       load = addHdr(PT_LOAD, flags);
2371       load->add(Out::elfHeader);
2372       load->add(Out::programHeaders);
2373     }
2374   }
2375 
2376   // PT_GNU_RELRO includes all sections that should be marked as
2377   // read-only by dynamic linker after processing relocations.
2378   // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
2379   // an error message if more than one PT_GNU_RELRO PHDR is required.
2380   PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
2381   bool inRelroPhdr = false;
2382   OutputSection *relroEnd = nullptr;
2383   for (OutputSection *sec : outputSections) {
2384     if (sec->partition != partNo || !needsPtLoad(sec))
2385       continue;
2386     if (isRelroSection(sec)) {
2387       inRelroPhdr = true;
2388       if (!relroEnd)
2389         relRo->add(sec);
2390       else
2391         error("section: " + sec->name + " is not contiguous with other relro" +
2392               " sections");
2393     } else if (inRelroPhdr) {
2394       inRelroPhdr = false;
2395       relroEnd = sec;
2396     }
2397   }
2398 
2399   for (OutputSection *sec : outputSections) {
2400     if (!needsPtLoad(sec))
2401       continue;
2402 
2403     // Normally, sections in partitions other than the current partition are
2404     // ignored. But partition number 255 is a special case: it contains the
2405     // partition end marker (.part.end). It needs to be added to the main
2406     // partition so that a segment is created for it in the main partition,
2407     // which will cause the dynamic loader to reserve space for the other
2408     // partitions.
2409     if (sec->partition != partNo) {
2410       if (isMain && sec->partition == 255)
2411         addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
2412       continue;
2413     }
2414 
2415     // Segments are contiguous memory regions that has the same attributes
2416     // (e.g. executable or writable). There is one phdr for each segment.
2417     // Therefore, we need to create a new phdr when the next section has
2418     // different flags or is loaded at a discontiguous address or memory
2419     // region using AT or AT> linker script command, respectively. At the same
2420     // time, we don't want to create a separate load segment for the headers,
2421     // even if the first output section has an AT or AT> attribute.
2422     uint64_t newFlags = computeFlags(sec->getPhdrFlags());
2423     bool sameLMARegion =
2424         load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
2425     if (!(load && newFlags == flags && sec != relroEnd &&
2426           sec->memRegion == load->firstSec->memRegion &&
2427           (sameLMARegion || load->lastSec == Out::programHeaders))) {
2428       load = addHdr(PT_LOAD, newFlags);
2429       flags = newFlags;
2430     }
2431 
2432     load->add(sec);
2433   }
2434 
2435   // Add a TLS segment if any.
2436   PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
2437   for (OutputSection *sec : outputSections)
2438     if (sec->partition == partNo && sec->flags & SHF_TLS)
2439       tlsHdr->add(sec);
2440   if (tlsHdr->firstSec)
2441     ret.push_back(tlsHdr);
2442 
2443   // Add an entry for .dynamic.
2444   if (OutputSection *sec = part.dynamic->getParent())
2445     addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
2446 
2447   if (relRo->firstSec)
2448     ret.push_back(relRo);
2449 
2450   // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
2451   if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
2452       part.ehFrame->getParent() && part.ehFrameHdr->getParent())
2453     addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
2454         ->add(part.ehFrameHdr->getParent());
2455 
2456   // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
2457   // the dynamic linker fill the segment with random data.
2458   if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
2459     addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
2460 
2461   if (config->zGnustack != GnuStackKind::None) {
2462     // PT_GNU_STACK is a special section to tell the loader to make the
2463     // pages for the stack non-executable. If you really want an executable
2464     // stack, you can pass -z execstack, but that's not recommended for
2465     // security reasons.
2466     unsigned perm = PF_R | PF_W;
2467     if (config->zGnustack == GnuStackKind::Exec)
2468       perm |= PF_X;
2469     addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
2470   }
2471 
2472   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2473   // is expected to perform W^X violations, such as calling mprotect(2) or
2474   // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2475   // OpenBSD.
2476   if (config->zWxneeded)
2477     addHdr(PT_OPENBSD_WXNEEDED, PF_X);
2478 
2479   if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
2480     addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
2481 
2482   // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the
2483   // same alignment.
2484   PhdrEntry *note = nullptr;
2485   for (OutputSection *sec : outputSections) {
2486     if (sec->partition != partNo)
2487       continue;
2488     if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
2489       if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment)
2490         note = addHdr(PT_NOTE, PF_R);
2491       note->add(sec);
2492     } else {
2493       note = nullptr;
2494     }
2495   }
2496   return ret;
2497 }
2498 
2499 template <class ELFT>
2500 void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
2501                                      unsigned pType, unsigned pFlags) {
2502   unsigned partNo = part.getNumber();
2503   auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
2504     return cmd->partition == partNo && cmd->type == shType;
2505   });
2506   if (i == outputSections.end())
2507     return;
2508 
2509   PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
2510   entry->add(*i);
2511   part.phdrs.push_back(entry);
2512 }
2513 
2514 // Place the first section of each PT_LOAD to a different page (of maxPageSize).
2515 // This is achieved by assigning an alignment expression to addrExpr of each
2516 // such section.
2517 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2518   const PhdrEntry *prev;
2519   auto pageAlign = [&](const PhdrEntry *p) {
2520     OutputSection *cmd = p->firstSec;
2521     if (!cmd)
2522       return;
2523     cmd->alignExpr = [align = cmd->alignment]() { return align; };
2524     if (!cmd->addrExpr) {
2525       // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid
2526       // padding in the file contents.
2527       //
2528       // When -z separate-code is used we must not have any overlap in pages
2529       // between an executable segment and a non-executable segment. We align to
2530       // the next maximum page size boundary on transitions between executable
2531       // and non-executable segments.
2532       //
2533       // SHT_LLVM_PART_EHDR marks the start of a partition. The partition
2534       // sections will be extracted to a separate file. Align to the next
2535       // maximum page size boundary so that we can find the ELF header at the
2536       // start. We cannot benefit from overlapping p_offset ranges with the
2537       // previous segment anyway.
2538       if (config->zSeparate == SeparateSegmentKind::Loadable ||
2539           (config->zSeparate == SeparateSegmentKind::Code && prev &&
2540            (prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
2541           cmd->type == SHT_LLVM_PART_EHDR)
2542         cmd->addrExpr = [] {
2543           return alignTo(script->getDot(), config->maxPageSize);
2544         };
2545       // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS,
2546       // it must be the RW. Align to p_align(PT_TLS) to make sure
2547       // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if
2548       // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS)
2549       // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not
2550       // be congruent to 0 modulo p_align(PT_TLS).
2551       //
2552       // Technically this is not required, but as of 2019, some dynamic loaders
2553       // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and
2554       // x86-64) doesn't make runtime address congruent to p_vaddr modulo
2555       // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same
2556       // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS
2557       // blocks correctly. We need to keep the workaround for a while.
2558       else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
2559         cmd->addrExpr = [] {
2560           return alignTo(script->getDot(), config->maxPageSize) +
2561                  alignTo(script->getDot() % config->maxPageSize,
2562                          Out::tlsPhdr->p_align);
2563         };
2564       else
2565         cmd->addrExpr = [] {
2566           return alignTo(script->getDot(), config->maxPageSize) +
2567                  script->getDot() % config->maxPageSize;
2568         };
2569     }
2570   };
2571 
2572   for (Partition &part : partitions) {
2573     prev = nullptr;
2574     for (const PhdrEntry *p : part.phdrs)
2575       if (p->p_type == PT_LOAD && p->firstSec) {
2576         pageAlign(p);
2577         prev = p;
2578       }
2579   }
2580 }
2581 
2582 // Compute an in-file position for a given section. The file offset must be the
2583 // same with its virtual address modulo the page size, so that the loader can
2584 // load executables without any address adjustment.
2585 static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
2586   // The first section in a PT_LOAD has to have congruent offset and address
2587   // modulo the maximum page size.
2588   if (os->ptLoad && os->ptLoad->firstSec == os)
2589     return alignTo(off, os->ptLoad->p_align, os->addr);
2590 
2591   // File offsets are not significant for .bss sections other than the first one
2592   // in a PT_LOAD/PT_TLS. By convention, we keep section offsets monotonically
2593   // increasing rather than setting to zero.
2594   if (os->type == SHT_NOBITS &&
2595       (!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
2596      return off;
2597 
2598   // If the section is not in a PT_LOAD, we just have to align it.
2599   if (!os->ptLoad)
2600     return alignTo(off, os->alignment);
2601 
2602   // If two sections share the same PT_LOAD the file offset is calculated
2603   // using this formula: Off2 = Off1 + (VA2 - VA1).
2604   OutputSection *first = os->ptLoad->firstSec;
2605   return first->offset + os->addr - first->addr;
2606 }
2607 
2608 // Set an in-file position to a given section and returns the end position of
2609 // the section.
2610 static uint64_t setFileOffset(OutputSection *os, uint64_t off) {
2611   off = computeFileOffset(os, off);
2612   os->offset = off;
2613 
2614   if (os->type == SHT_NOBITS)
2615     return off;
2616   return off + os->size;
2617 }
2618 
2619 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2620   // Compute the minimum LMA of all non-empty non-NOBITS sections as minAddr.
2621   auto needsOffset = [](OutputSection &sec) {
2622     return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
2623   };
2624   uint64_t minAddr = UINT64_MAX;
2625   for (OutputSection *sec : outputSections)
2626     if (needsOffset(*sec)) {
2627       sec->offset = sec->getLMA();
2628       minAddr = std::min(minAddr, sec->offset);
2629     }
2630 
2631   // Sections are laid out at LMA minus minAddr.
2632   fileSize = 0;
2633   for (OutputSection *sec : outputSections)
2634     if (needsOffset(*sec)) {
2635       sec->offset -= minAddr;
2636       fileSize = std::max(fileSize, sec->offset + sec->size);
2637     }
2638 }
2639 
2640 static std::string rangeToString(uint64_t addr, uint64_t len) {
2641   return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
2642 }
2643 
2644 // Assign file offsets to output sections.
2645 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2646   uint64_t off = 0;
2647   off = setFileOffset(Out::elfHeader, off);
2648   off = setFileOffset(Out::programHeaders, off);
2649 
2650   PhdrEntry *lastRX = nullptr;
2651   for (Partition &part : partitions)
2652     for (PhdrEntry *p : part.phdrs)
2653       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2654         lastRX = p;
2655 
2656   // Layout SHF_ALLOC sections before non-SHF_ALLOC sections. A non-SHF_ALLOC
2657   // will not occupy file offsets contained by a PT_LOAD.
2658   for (OutputSection *sec : outputSections) {
2659     if (!(sec->flags & SHF_ALLOC))
2660       continue;
2661     off = setFileOffset(sec, off);
2662 
2663     // If this is a last section of the last executable segment and that
2664     // segment is the last loadable segment, align the offset of the
2665     // following section to avoid loading non-segments parts of the file.
2666     if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
2667         lastRX->lastSec == sec)
2668       off = alignTo(off, config->commonPageSize);
2669   }
2670   for (OutputSection *sec : outputSections)
2671     if (!(sec->flags & SHF_ALLOC))
2672       off = setFileOffset(sec, off);
2673 
2674   sectionHeaderOff = alignTo(off, config->wordsize);
2675   fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
2676 
2677   // Our logic assumes that sections have rising VA within the same segment.
2678   // With use of linker scripts it is possible to violate this rule and get file
2679   // offset overlaps or overflows. That should never happen with a valid script
2680   // which does not move the location counter backwards and usually scripts do
2681   // not do that. Unfortunately, there are apps in the wild, for example, Linux
2682   // kernel, which control segment distribution explicitly and move the counter
2683   // backwards, so we have to allow doing that to support linking them. We
2684   // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2685   // we want to prevent file size overflows because it would crash the linker.
2686   for (OutputSection *sec : outputSections) {
2687     if (sec->type == SHT_NOBITS)
2688       continue;
2689     if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
2690       error("unable to place section " + sec->name + " at file offset " +
2691             rangeToString(sec->offset, sec->size) +
2692             "; check your linker script for overflows");
2693   }
2694 }
2695 
2696 // Finalize the program headers. We call this function after we assign
2697 // file offsets and VAs to all sections.
2698 template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
2699   for (PhdrEntry *p : part.phdrs) {
2700     OutputSection *first = p->firstSec;
2701     OutputSection *last = p->lastSec;
2702 
2703     if (first) {
2704       p->p_filesz = last->offset - first->offset;
2705       if (last->type != SHT_NOBITS)
2706         p->p_filesz += last->size;
2707 
2708       p->p_memsz = last->addr + last->size - first->addr;
2709       p->p_offset = first->offset;
2710       p->p_vaddr = first->addr;
2711 
2712       // File offsets in partitions other than the main partition are relative
2713       // to the offset of the ELF headers. Perform that adjustment now.
2714       if (part.elfHeader)
2715         p->p_offset -= part.elfHeader->getParent()->offset;
2716 
2717       if (!p->hasLMA)
2718         p->p_paddr = first->getLMA();
2719     }
2720 
2721     if (p->p_type == PT_GNU_RELRO) {
2722       p->p_align = 1;
2723       // musl/glibc ld.so rounds the size down, so we need to round up
2724       // to protect the last page. This is a no-op on FreeBSD which always
2725       // rounds up.
2726       p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) -
2727                    p->p_offset;
2728     }
2729   }
2730 }
2731 
2732 // A helper struct for checkSectionOverlap.
2733 namespace {
2734 struct SectionOffset {
2735   OutputSection *sec;
2736   uint64_t offset;
2737 };
2738 } // namespace
2739 
2740 // Check whether sections overlap for a specific address range (file offsets,
2741 // load and virtual addresses).
2742 static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections,
2743                          bool isVirtualAddr) {
2744   llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
2745     return a.offset < b.offset;
2746   });
2747 
2748   // Finding overlap is easy given a vector is sorted by start position.
2749   // If an element starts before the end of the previous element, they overlap.
2750   for (size_t i = 1, end = sections.size(); i < end; ++i) {
2751     SectionOffset a = sections[i - 1];
2752     SectionOffset b = sections[i];
2753     if (b.offset >= a.offset + a.sec->size)
2754       continue;
2755 
2756     // If both sections are in OVERLAY we allow the overlapping of virtual
2757     // addresses, because it is what OVERLAY was designed for.
2758     if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
2759       continue;
2760 
2761     errorOrWarn("section " + a.sec->name + " " + name +
2762                 " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
2763                 " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
2764                 b.sec->name + " range is " +
2765                 rangeToString(b.offset, b.sec->size));
2766   }
2767 }
2768 
2769 // Check for overlapping sections and address overflows.
2770 //
2771 // In this function we check that none of the output sections have overlapping
2772 // file offsets. For SHF_ALLOC sections we also check that the load address
2773 // ranges and the virtual address ranges don't overlap
2774 template <class ELFT> void Writer<ELFT>::checkSections() {
2775   // First, check that section's VAs fit in available address space for target.
2776   for (OutputSection *os : outputSections)
2777     if ((os->addr + os->size < os->addr) ||
2778         (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX))
2779       errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
2780                   " of size 0x" + utohexstr(os->size) +
2781                   " exceeds available address space");
2782 
2783   // Check for overlapping file offsets. In this case we need to skip any
2784   // section marked as SHT_NOBITS. These sections don't actually occupy space in
2785   // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2786   // binary is specified only add SHF_ALLOC sections are added to the output
2787   // file so we skip any non-allocated sections in that case.
2788   std::vector<SectionOffset> fileOffs;
2789   for (OutputSection *sec : outputSections)
2790     if (sec->size > 0 && sec->type != SHT_NOBITS &&
2791         (!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
2792       fileOffs.push_back({sec, sec->offset});
2793   checkOverlap("file", fileOffs, false);
2794 
2795   // When linking with -r there is no need to check for overlapping virtual/load
2796   // addresses since those addresses will only be assigned when the final
2797   // executable/shared object is created.
2798   if (config->relocatable)
2799     return;
2800 
2801   // Checking for overlapping virtual and load addresses only needs to take
2802   // into account SHF_ALLOC sections since others will not be loaded.
2803   // Furthermore, we also need to skip SHF_TLS sections since these will be
2804   // mapped to other addresses at runtime and can therefore have overlapping
2805   // ranges in the file.
2806   std::vector<SectionOffset> vmas;
2807   for (OutputSection *sec : outputSections)
2808     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2809       vmas.push_back({sec, sec->addr});
2810   checkOverlap("virtual address", vmas, true);
2811 
2812   // Finally, check that the load addresses don't overlap. This will usually be
2813   // the same as the virtual addresses but can be different when using a linker
2814   // script with AT().
2815   std::vector<SectionOffset> lmas;
2816   for (OutputSection *sec : outputSections)
2817     if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
2818       lmas.push_back({sec, sec->getLMA()});
2819   checkOverlap("load address", lmas, false);
2820 }
2821 
2822 // The entry point address is chosen in the following ways.
2823 //
2824 // 1. the '-e' entry command-line option;
2825 // 2. the ENTRY(symbol) command in a linker control script;
2826 // 3. the value of the symbol _start, if present;
2827 // 4. the number represented by the entry symbol, if it is a number;
2828 // 5. the address 0.
2829 static uint64_t getEntryAddr() {
2830   // Case 1, 2 or 3
2831   if (Symbol *b = symtab->find(config->entry))
2832     return b->getVA();
2833 
2834   // Case 4
2835   uint64_t addr;
2836   if (to_integer(config->entry, addr))
2837     return addr;
2838 
2839   // Case 5
2840   if (config->warnMissingEntry)
2841     warn("cannot find entry symbol " + config->entry +
2842          "; not setting start address");
2843   return 0;
2844 }
2845 
2846 static uint16_t getELFType() {
2847   if (config->isPic)
2848     return ET_DYN;
2849   if (config->relocatable)
2850     return ET_REL;
2851   return ET_EXEC;
2852 }
2853 
2854 template <class ELFT> void Writer<ELFT>::writeHeader() {
2855   writeEhdr<ELFT>(Out::bufferStart, *mainPart);
2856   writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
2857 
2858   auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
2859   eHdr->e_type = getELFType();
2860   eHdr->e_entry = getEntryAddr();
2861   eHdr->e_shoff = sectionHeaderOff;
2862 
2863   // Write the section header table.
2864   //
2865   // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2866   // and e_shstrndx fields. When the value of one of these fields exceeds
2867   // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2868   // use fields in the section header at index 0 to store
2869   // the value. The sentinel values and fields are:
2870   // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2871   // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2872   auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
2873   size_t num = outputSections.size() + 1;
2874   if (num >= SHN_LORESERVE)
2875     sHdrs->sh_size = num;
2876   else
2877     eHdr->e_shnum = num;
2878 
2879   uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
2880   if (strTabIndex >= SHN_LORESERVE) {
2881     sHdrs->sh_link = strTabIndex;
2882     eHdr->e_shstrndx = SHN_XINDEX;
2883   } else {
2884     eHdr->e_shstrndx = strTabIndex;
2885   }
2886 
2887   for (OutputSection *sec : outputSections)
2888     sec->writeHeaderTo<ELFT>(++sHdrs);
2889 }
2890 
2891 // Open a result file.
2892 template <class ELFT> void Writer<ELFT>::openFile() {
2893   uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
2894   if (fileSize != size_t(fileSize) || maxSize < fileSize) {
2895     std::string msg;
2896     raw_string_ostream s(msg);
2897     s << "output file too large: " << Twine(fileSize) << " bytes\n"
2898       << "section sizes:\n";
2899     for (OutputSection *os : outputSections)
2900       s << os->name << ' ' << os->size << "\n";
2901     error(s.str());
2902     return;
2903   }
2904 
2905   unlinkAsync(config->outputFile);
2906   unsigned flags = 0;
2907   if (!config->relocatable)
2908     flags |= FileOutputBuffer::F_executable;
2909   if (!config->mmapOutputFile)
2910     flags |= FileOutputBuffer::F_no_mmap;
2911   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
2912       FileOutputBuffer::create(config->outputFile, fileSize, flags);
2913 
2914   if (!bufferOrErr) {
2915     error("failed to open " + config->outputFile + ": " +
2916           llvm::toString(bufferOrErr.takeError()));
2917     return;
2918   }
2919   buffer = std::move(*bufferOrErr);
2920   Out::bufferStart = buffer->getBufferStart();
2921 }
2922 
2923 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2924   for (OutputSection *sec : outputSections)
2925     if (sec->flags & SHF_ALLOC)
2926       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2927 }
2928 
2929 static void fillTrap(uint8_t *i, uint8_t *end) {
2930   for (; i + 4 <= end; i += 4)
2931     memcpy(i, &target->trapInstr, 4);
2932 }
2933 
2934 // Fill the last page of executable segments with trap instructions
2935 // instead of leaving them as zero. Even though it is not required by any
2936 // standard, it is in general a good thing to do for security reasons.
2937 //
2938 // We'll leave other pages in segments as-is because the rest will be
2939 // overwritten by output sections.
2940 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2941   for (Partition &part : partitions) {
2942     // Fill the last page.
2943     for (PhdrEntry *p : part.phdrs)
2944       if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
2945         fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz,
2946                                               config->commonPageSize),
2947                  Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz,
2948                                             config->commonPageSize));
2949 
2950     // Round up the file size of the last segment to the page boundary iff it is
2951     // an executable segment to ensure that other tools don't accidentally
2952     // trim the instruction padding (e.g. when stripping the file).
2953     PhdrEntry *last = nullptr;
2954     for (PhdrEntry *p : part.phdrs)
2955       if (p->p_type == PT_LOAD)
2956         last = p;
2957 
2958     if (last && (last->p_flags & PF_X))
2959       last->p_memsz = last->p_filesz =
2960           alignTo(last->p_filesz, config->commonPageSize);
2961   }
2962 }
2963 
2964 // Write section contents to a mmap'ed file.
2965 template <class ELFT> void Writer<ELFT>::writeSections() {
2966   // In -r or --emit-relocs mode, write the relocation sections first as in
2967   // ELf_Rel targets we might find out that we need to modify the relocated
2968   // section while doing it.
2969   for (OutputSection *sec : outputSections)
2970     if (sec->type == SHT_REL || sec->type == SHT_RELA)
2971       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2972 
2973   for (OutputSection *sec : outputSections)
2974     if (sec->type != SHT_REL && sec->type != SHT_RELA)
2975       sec->writeTo<ELFT>(Out::bufferStart + sec->offset);
2976 
2977   // Finally, check that all dynamic relocation addends were written correctly.
2978   if (config->checkDynamicRelocs && config->writeAddends) {
2979     for (OutputSection *sec : outputSections)
2980       if (sec->type == SHT_REL || sec->type == SHT_RELA)
2981         sec->checkDynRelAddends(Out::bufferStart);
2982   }
2983 }
2984 
2985 // Computes a hash value of Data using a given hash function.
2986 // In order to utilize multiple cores, we first split data into 1MB
2987 // chunks, compute a hash for each chunk, and then compute a hash value
2988 // of the hash values.
2989 static void
2990 computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
2991             llvm::ArrayRef<uint8_t> data,
2992             std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
2993   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
2994   std::vector<uint8_t> hashes(chunks.size() * hashBuf.size());
2995 
2996   // Compute hash values.
2997   parallelForEachN(0, chunks.size(), [&](size_t i) {
2998     hashFn(hashes.data() + i * hashBuf.size(), chunks[i]);
2999   });
3000 
3001   // Write to the final output buffer.
3002   hashFn(hashBuf.data(), hashes);
3003 }
3004 
3005 template <class ELFT> void Writer<ELFT>::writeBuildId() {
3006   if (!mainPart->buildId || !mainPart->buildId->getParent())
3007     return;
3008 
3009   if (config->buildId == BuildIdKind::Hexstring) {
3010     for (Partition &part : partitions)
3011       part.buildId->writeBuildId(config->buildIdVector);
3012     return;
3013   }
3014 
3015   // Compute a hash of all sections of the output file.
3016   size_t hashSize = mainPart->buildId->hashSize;
3017   std::vector<uint8_t> buildId(hashSize);
3018   llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)};
3019 
3020   switch (config->buildId) {
3021   case BuildIdKind::Fast:
3022     computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
3023       write64le(dest, xxHash64(arr));
3024     });
3025     break;
3026   case BuildIdKind::Md5:
3027     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3028       memcpy(dest, MD5::hash(arr).data(), hashSize);
3029     });
3030     break;
3031   case BuildIdKind::Sha1:
3032     computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
3033       memcpy(dest, SHA1::hash(arr).data(), hashSize);
3034     });
3035     break;
3036   case BuildIdKind::Uuid:
3037     if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize))
3038       error("entropy source failure: " + ec.message());
3039     break;
3040   default:
3041     llvm_unreachable("unknown BuildIdKind");
3042   }
3043   for (Partition &part : partitions)
3044     part.buildId->writeBuildId(buildId);
3045 }
3046 
3047 template void elf::createSyntheticSections<ELF32LE>();
3048 template void elf::createSyntheticSections<ELF32BE>();
3049 template void elf::createSyntheticSections<ELF64LE>();
3050 template void elf::createSyntheticSections<ELF64BE>();
3051 
3052 template void elf::writeResult<ELF32LE>();
3053 template void elf::writeResult<ELF32BE>();
3054 template void elf::writeResult<ELF64LE>();
3055 template void elf::writeResult<ELF64BE>();
3056