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