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