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