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