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